I’m using a custom loop to display my events on a page, I get it fine ordering by the event start date using the below:
$args = array(
'post_type' => 'event',
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => '_event_start_date');
$loop = new WP_Query( $args );
But the meta_key option only allows one value. How to use two values (_event_start_date
and _event_start_time
)?
This is something that WordPress added support for in 4.2: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
In your case you'll probably want to do something like this:
$args = array(
'post_type' => 'event',
'meta_query' => array(
'relation' => 'AND',
'event_start_date_clause' => array(
'key' => '_event_start_date',
'compare' => 'EXISTS',
),
'event_start_time_clause' => array(
'key' => '_event_start_time',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'event_start_date_clause' => 'ASC',
'event_start_time_clause' => 'ASC',
),
);
$loop = new WP_Query( $args );
You have to use meta_query at add your meta keys as everyone said, but also you have to customize order by function.
$args = array(
'post_type' => 'event',
'meta_key' => '_event_start_date',
'meta_query' => array(
array('key' => '_event_start_date'),
array('key' => '_event_start_time')
),
);
add_filter('posts_orderby','customorderby');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','customorderby');
And put this on your functions.php
function customorderby($orderby) {
return 'mt1.meta_value ASC, mt2.meta_value ASC';
}
You can read more at http://dotnordic.se/sorting-wordpress-posts-by-several-numeric-custom-fields/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With