WP_Query sort by multiple custom fields
-
I have a custom post type with two acf fields, ‘type’ (options are: news and event) and ‘date’.
On the archive page i want to query the results by first showing the upcoming events (ASC) and then all news (DESC).
With the help of Google i found several solutions. For example https://facetwp.com/wp_query-sort-by-multiple-custom-fields/Code below is my variant but it does not work. If i debug the query the order by clause is missing at all. Does anybody know what i am doing wrong?
add_action('pre_get_posts', function ($query) { if (!is_admin() and $query->is_archive('news') and $query->is_main_query()) { $meta_query = []; $meta_query[] = [ 'relation' => 'OR', 'event_clause' => [ 'relation' => 'AND', [ 'key' => 'type', 'value' => 'event', 'compare' => '=', ], [ 'key' => 'from', 'value' => date('Ymd'), 'compare' => '>', 'type' => 'DATE' ], ], 'news_clause' => [ 'relation' => 'AND', [ 'key' => 'type', 'value' => 'news', 'compare' => '=' ], ] ]; $orderby = [ 'event_clause' => 'ASC', 'news_clause' => 'DESC' ]; $query->set('meta_query', $meta_query); $query->set('orderby', $orderby); } });
Debug query:
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND ( ( ( ( wp_postmeta.meta_key = 'type' AND wp_postmeta.meta_value = 'event' ) AND ( mt1.meta_key = 'from' AND CAST(mt1.meta_value AS DATE) > '20240117' ) ) OR ( ( mt2.meta_key = 'type' AND mt2.meta_value = 'news' ) AND ( mt3.meta_key = 'from' AND CAST(mt3.meta_value AS DATE) > '0' ) ) ) ) AND ((wp_posts.post_type = 'news' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'archived' OR wp_posts.post_status = 'private'))) GROUP BY wp_posts.ID LIMIT 0, 100
It’s missing the order by clause.
Viewing 10 replies - 1 through 10 (of 10 total)
Viewing 10 replies - 1 through 10 (of 10 total)
- The topic ‘WP_Query sort by multiple custom fields’ is closed to new replies.