How to orderby multiple meta fields with another meta query

admin2025-06-06  2

I have a custom post type ”events” with meta fields ”startdate” and ”enddate”. Archive query already uses meta query to show only upcoming or ongoing events, but in addition I need to order by both meta fields. I can't figure out what the meta query should be, so it works for both uses. Or am I doing something wrong?

This is part of the query, with the simple orderby that I need to replace. Anyone got any ideas how to add ”...orderby startdate, enddate” to this?

$meta_query = array(
    'relation' => 'OR',
    'enddate' => array (
        'key' => 'enddate',
        'value' => date( 'Y-m-d' ),
        'compare' => '>='
    ),
    'startdate' => array (
        'key' => 'startdate',
        'value' => date( 'Y-m-d' ),
        'compare' => '>=',
    )
);
$query->set('meta_query',$meta_query);
$query->set('orderby', 'meta_value');   
$query->set('meta_key', 'startdate');

I have a custom post type ”events” with meta fields ”startdate” and ”enddate”. Archive query already uses meta query to show only upcoming or ongoing events, but in addition I need to order by both meta fields. I can't figure out what the meta query should be, so it works for both uses. Or am I doing something wrong?

This is part of the query, with the simple orderby that I need to replace. Anyone got any ideas how to add ”...orderby startdate, enddate” to this?

$meta_query = array(
    'relation' => 'OR',
    'enddate' => array (
        'key' => 'enddate',
        'value' => date( 'Y-m-d' ),
        'compare' => '>='
    ),
    'startdate' => array (
        'key' => 'startdate',
        'value' => date( 'Y-m-d' ),
        'compare' => '>=',
    )
);
$query->set('meta_query',$meta_query);
$query->set('orderby', 'meta_value');   
$query->set('meta_key', 'startdate');
Share Improve this question asked Nov 23, 2018 at 15:54 Petri V.Petri V. 111 bronze badge 2
  • Welcome to WPSE! There may need to be some more context to your question. One thing that I would question is the format of the data. You'll have a hard time with querying (if >=) and sorting as a date because meta data is a string - it's never formatted as a date. One way around that is to store post meta that are dates using Unix epoch time (because that can be sorted as a string). Just a suggestion to look into. – butlerblog Commented Nov 24, 2018 at 0:45
  • Thanks for your feedback. The format is yyyy-mm-dd which might not be the best way to store dates, but it worked fine before migrating the data into Wordpress. – Petri V. Commented Nov 24, 2018 at 9:34
Add a comment  | 

1 Answer 1

Reset to default 0

You've already named the clauses in your meta query, so you can reference these directly in the orderby argument:

$query->set(
    'orderby',
    array(
        'enddate' => 'DESC',
        'startdate' => 'DESC'
    )
);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749155984a316841.html

最新回复(0)