Advertisement
geminilabs

[site-reviews] Change sorting of a Query Loop block

Nov 18th, 2022
1,065
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. /**
  2.  * Changes the sorting of a Query Loop block
  3.  *
  4.  * To use, add one of the following classes to the Query Loop block (in the Advanced panel of the block settings):
  5.  * - sort-by-average
  6.  * - sort-by-ranking
  7.  * - sort-by-reviews
  8.  */
  9. add_filter('pre_render_block', function ($prerender, $block) {
  10.     if ('core/query' !== $block['blockName']) {
  11.         return $prerender;
  12.     }
  13.     $sorting = [
  14.         'sort-by-average' => '_glsr_average',
  15.         'sort-by-ranking' => '_glsr_ranking',
  16.         'sort-by-reviews' => '_glsr_reviews',
  17.     ];
  18.     if (empty($block['attrs']['className']) || !array_key_exists($block['attrs']['className'], $sorting)) {
  19.         return $prerender;
  20.     }
  21.     $sortKey = $sorting[$block['attrs']['className']];
  22.     add_filter('query_loop_block_query_vars', function ($query) use ($sortKey) {
  23.         $query['meta_query'] = [
  24.             'relation' => 'OR',
  25.             ['key' => $sortKey, 'compare' => 'NOT EXISTS'], // this comes first!
  26.             ['key' => $sortKey, 'compare' => 'EXISTS'],
  27.         ];
  28.         $query['orderby'] = 'meta_value_num';
  29.         glsr_log($query);
  30.         return $query;
  31.     });
  32. }, 10, 2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement