WP_Query order by two values
WP_Query order by two values
Im trying to make WP_Query to order by two different values, but i cant figure how to do this. Im trying to get events in one query by ending time. There is custom ending_date_time field in every event with datetime of value YYYY-MM-DD H:i:s. I need query to get values so first one is event that is closest to ending and so on, and if there is events that have ended, they come after those events that havent end yet.
With MySQL i would do this kind of thing like this:
SELECT * FROM events ORDER BY event_endtime < NOW(), event_endtime ASC
meta_key=ending_date_time
orderby
meta_value
1 Answer
1
With this query you get the events for the now and in the future.
$today = date( 'YYYY-MM-DD H:i:s' );
$args = array(
'post_type' => 'events',
'orderby' => 'event_endtime',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'event_endtime',
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
)
)
):
$query = new WP_Query( $args );
If you want to past events you have to change 'compare' => '<='.
'compare' => '<='
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
From the codex page: "orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed. ". As for ordering by meta value: you need a
meta_key=ending_date_timein your query, and then yourorderbyparameter should be set tometa_value. I'm unsure whether you must order ASC or DESC to have to closest dates first - maybe just try it out.– Michael
Sep 16 '18 at 23:47