ORDER BY custom field value out of where clause

Based on example here https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

I'd like to modify the query

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

to be able to get all posts where state is 'Wisconsin' OR state is 'California' and ORDER BY population DESC.

I'm failing in writing such query in WP.

Any tips would be much appreciated.

Topic meta-query order custom-field sort Wordpress

Category Web


Define that a population has to be set, and make a list of allowed states as an array.

Afterwards, take population into the orderby and sort it DESC.

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => array( 'Wisconsin', 'California' ), //allowed values
            'compare' => 'IN' // state must be in array above
        ),
        'population_clause' => array(
            'key' => 'population',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array(
        'population_clause' => 'DESC',
    ),
) );

To have two different condition combined with an OR:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'OR',
        'state_clause' => array(
            'key' => 'state',
            'value' => array( 'Wisconsin' ), // allowed values
            'compare' => 'IN' // state must be in array above
        ),
        'state_clause' => array(
            'key' => 'timezone',
            'value' => 'central',
            'compare' => '='
        ),
        'population_clause' => array(
            'key' => 'population',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array(
        'population_clause' => 'DESC',
    ),
) );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.