Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class WpMainQueryFilter {
- public function __construct() {
- add_action( 'pre_get_posts', [ $this, 'filterQuery' ] );
- }
- public function filterQuery( WP_Query $query ): void {
- if ( ! $query->is_main_query() ) {
- return;
- }
- $filterBy = $_GET['select'] ?? '';
- if ( ! $filterBy ) {
- return;
- }
- switch ( $filterBy ) {
- case in_array( $filterBy, [ 'dl7', 'dl14', 'dl30' ] ):
- add_filter( 'posts_fields', [ $this, 'selectDownloads' ], 10, 2 );
- add_filter( 'posts_join', [ $this, 'joinDownloads' ], 10, 2 );
- add_filter( 'posts_orderby', [ $this, 'orderByDownloads' ], 10, 2 );
- break;
- }
- }
- public function selectDownloads( string $select, WP_Query $query ): string {
- if ( ! $query->is_main_query() ) {
- return $select;
- }
- $select .= ", dl_stats.dl as dl";
- return $select;
- }
- public function joinDownloads( string $join, WP_Query $query ): string {
- if ( ! $query->is_main_query() ) {
- return $join;
- }
- $days = ltrim( $_GET['select'], 'dl' );
- $aggregateQuery = "
- SELECT post_id, SUM(dl) as dl
- FROM wp_day_download
- WHERE date >= DATE_ADD(CURRENT_TIMESTAMP,INTERVAL -$days DAY)
- GROUP BY post_id
- ORDER BY SUM(dl) DESC";
- $join .= " INNER JOIN ($aggregateQuery) as dl_stats ON wp_posts.ID = dl_stats.post_id";
- return $join;
- }
- public function orderByDownloads( string $orderBy, WP_Query $query ): string {
- if ( ! $query->is_main_query() ) {
- return $orderBy;
- }
- return "dl DESC";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment