PluginProbe
Powerkit – Supercharge your WordPress Site / 2.4.4
Powerkit – Supercharge your WordPress Site v2.4.4
3.1.1 3.1.0 3.0.9 3.0.8 trunk 2.2.6 2.2.7 2.2.8 2.2.9 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.8 2.3.9 2.4.0 2.4.1 2.4.2 2.4.3 2.4.4 2.4.5 All 87 releases
powerkit / modules / post-views / helpers / query-powerkit-post-views.php

query-powerkit-post-views.php in Powerkit – Supercharge your WordPress Site 2.4.4, at modules/post-views/helpers/query-powerkit-post-views.php

91 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Post Views Query
4 *
5 * @package Powerkit
6 * @subpackage Modules/Query
7 */
8
9 class Powerkit_Post_Views_Query {
10
11 /**
12 * Construct.
13 */
14 public function __construct() {
15 add_action( 'pre_get_posts', array( $this, 'extend_pre_query' ), 1 );
16 add_filter( 'posts_join', array( $this, 'posts_join' ), 10, 2 );
17 add_filter( 'posts_groupby', array( $this, 'posts_groupby' ), 10, 2 );
18 add_filter( 'posts_orderby', array( $this, 'posts_orderby' ), 10, 2 );
19 }
20
21 /**
22 * Extend query with post_views orderby parameter.
23 *
24 * @param object $query The query.
25 */
26 public function extend_pre_query( $query ) {
27 if ( isset( $query->query_vars['orderby'] ) && 'pk_post_views' === $query->query_vars['orderby'] ) {
28 $query->pk_post_views = true;
29 }
30 }
31
32 /**
33 * Modify the db query to use post_views parameter.
34 *
35 * @param string $join The join.
36 * @param object $query The query.
37 */
38 public function posts_join( $join, $query ) {
39
40 if ( isset( $query->pk_post_views ) && $query->pk_post_views ) {
41 global $wpdb;
42
43 $join .= ' LEFT JOIN ' . $wpdb->prefix . 'pk_post_views ON ' . $wpdb->prefix . 'pk_post_views.id = ' . $wpdb->prefix . 'posts.ID';
44 }
45
46 return $join;
47 }
48
49 /**
50 * Group posts using the post ID.
51 *
52 * @param string $groupby The groupby.
53 * @param object $query The query.
54 */
55 public function posts_groupby( $groupby, $query ) {
56
57 if ( isset( $query->pk_post_views ) && $query->pk_post_views ) {
58 global $wpdb;
59
60 $groupby = trim( $groupby );
61
62 if ( false === strpos( $groupby, $wpdb->prefix . 'posts.ID' ) ) {
63 $groupby = ( '' !== $groupby ? $groupby . ', ' : '' ) . $wpdb->prefix . 'posts.ID';
64 }
65 }
66
67 return $groupby;
68 }
69
70 /**
71 * Order posts by post views.
72 *
73 * @param string $orderby The orderby.
74 * @param object $query The query.
75 */
76 public function posts_orderby( $orderby, $query ) {
77 if ( isset( $query->pk_post_views ) && $query->pk_post_views ) {
78 global $wpdb;
79
80 $order = $query->get( 'order' );
81
82 $orderby = $wpdb->prefix . 'pk_post_views.count ' . $order . ', ' . $wpdb->prefix . 'posts.ID ' . $order;
83 }
84
85 return $orderby;
86 }
87 }
88
89
90 new Powerkit_Post_Views_Query();
91