How to order by multiple meta keys?

user1280853 picture user1280853 · Jul 19, 2013 · Viewed 15.6k times · Source

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)?

Answer

Wes Moberly picture Wes Moberly · Feb 20, 2016

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