columns.php
10 years ago
counter.php
10 years ago
cron.php
10 years ago
frontend.php
10 years ago
functions.php
10 years ago
query.php
10 years ago
settings.php
10 years ago
update.php
10 years ago
widgets.php
10 years ago
query.php
69 lines
| 1 | <?php |
| 2 | if ( ! defined( 'ABSPATH' ) ) |
| 3 | exit; |
| 4 | |
| 5 | new Post_Views_Counter_Query(); |
| 6 | |
| 7 | class Post_Views_Counter_Query { |
| 8 | |
| 9 | public function __construct() { |
| 10 | // actions |
| 11 | add_action( 'pre_get_posts', array( &$this, 'extend_pre_query' ), 9 ); |
| 12 | |
| 13 | // filters |
| 14 | add_filter( 'posts_join', array( &$this, 'posts_join' ), 10, 2 ); |
| 15 | add_filter( 'posts_groupby', array( &$this, 'posts_groupby' ), 10, 2 ); |
| 16 | add_filter( 'posts_orderby', array( &$this, 'posts_orderby' ), 10, 2 ); |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Extend query with post_views orderby parameter. |
| 21 | */ |
| 22 | public function extend_pre_query( $query ) { |
| 23 | if ( isset( $query->query_vars['orderby'] ) && $query->query_vars['orderby'] === 'post_views' ) |
| 24 | $query->order_by_post_views = true; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Modify the db query to use post_views parameter. |
| 29 | */ |
| 30 | public function posts_join( $join, $query ) { |
| 31 | global $wpdb; |
| 32 | |
| 33 | // is it sorted by post views? |
| 34 | if ( isset( $query->order_by_post_views ) && $query->order_by_post_views ) |
| 35 | $join .= " LEFT JOIN " . $wpdb->prefix . "post_views pvc ON pvc.id = " . $wpdb->prefix . "posts.ID AND pvc.type = 4"; |
| 36 | |
| 37 | return $join; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Group posts using the post ID. |
| 42 | */ |
| 43 | public function posts_groupby( $groupby, $query ) { |
| 44 | global $wpdb; |
| 45 | |
| 46 | // is it sorted by post views? |
| 47 | if ( isset( $query->order_by_post_views ) && $query->order_by_post_views ) |
| 48 | $groupby = (trim( $groupby ) !== '' ? $groupby . ', ' : '') . $wpdb->prefix . 'posts.ID'; |
| 49 | |
| 50 | return $groupby; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Order posts by post views. |
| 55 | */ |
| 56 | public function posts_orderby( $orderby, $query ) { |
| 57 | global $wpdb; |
| 58 | |
| 59 | // is it sorted by post views? |
| 60 | if ( isset( $query->order_by_post_views ) && $query->order_by_post_views ) { |
| 61 | $order = $query->get( 'order' ); |
| 62 | $orderby = 'pvc.count ' . $order . ', ' . $wpdb->prefix . 'posts.ID ' . $order; |
| 63 | } |
| 64 | |
| 65 | return $orderby; |
| 66 | } |
| 67 | |
| 68 | } |
| 69 |