Order by multiple meta key and meta value [closed]

meta_query is an array of meta clauses. For example:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
) );

You can use an associative array, with a key for each meta clause:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
) );

Then, you can use that keys in the order_by argument, with one:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => 'city_clause', // Results will be ordered by 'city' meta values.
) );

Or more clauses:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array( 
        'city_clause' => 'ASC',
        'state_clause' => 'DESC',
    ),
) );

Example taken from this post in Make WordPres Core blog.

Leave a Comment