Guest User

Untitled

a guest
Nov 4th, 2022
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.50 KB | None | 0 0
  1. class WpMainQueryFilter {
  2.     public function __construct() {
  3.  
  4.         add_action( 'pre_get_posts', [ $this, 'filterQuery' ] );
  5.     }
  6.  
  7.     public function filterQuery( WP_Query $query ): void {
  8.         if ( ! $query->is_main_query() ) {
  9.             return;
  10.         }
  11.  
  12.         $filterBy = $_GET['select'] ?? '';
  13.  
  14.         if ( ! $filterBy ) {
  15.             return;
  16.         }
  17.  
  18.         switch ( $filterBy ) {
  19.             case in_array( $filterBy, [ 'dl7', 'dl14', 'dl30' ] ):
  20.                 add_filter( 'posts_fields', [ $this, 'selectDownloads' ], 10, 2 );
  21.                 add_filter( 'posts_join', [ $this, 'joinDownloads' ], 10, 2 );
  22.                 add_filter( 'posts_orderby', [ $this, 'orderByDownloads' ], 10, 2 );
  23.                 break;
  24.         }
  25.     }
  26.  
  27.     public function selectDownloads( string $select, WP_Query $query ): string {
  28.  
  29.         if ( ! $query->is_main_query() ) {
  30.             return $select;
  31.         }
  32.  
  33.         $select .= ", dl_stats.dl as dl";
  34.  
  35.         return $select;
  36.     }
  37.  
  38.     public function joinDownloads( string $join, WP_Query $query ): string {
  39.  
  40.         if ( ! $query->is_main_query() ) {
  41.             return $join;
  42.         }
  43.  
  44.         $days = ltrim( $_GET['select'], 'dl' );
  45.  
  46.         $aggregateQuery = "
  47.                 SELECT post_id, SUM(dl) as dl
  48.                 FROM wp_day_download
  49.                 WHERE date >= DATE_ADD(CURRENT_TIMESTAMP,INTERVAL -$days DAY)
  50.                 GROUP BY post_id
  51.                 ORDER BY SUM(dl) DESC";
  52.  
  53.         $join .= " INNER JOIN ($aggregateQuery) as dl_stats ON wp_posts.ID = dl_stats.post_id";
  54.  
  55.         return $join;
  56.     }
  57.  
  58.     public function orderByDownloads( string $orderBy, WP_Query $query ): string {
  59.  
  60.         if ( ! $query->is_main_query() ) {
  61.             return $orderBy;
  62.         }
  63.  
  64.         return "dl DESC";
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment