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');
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'
)
);
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