0

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.

2

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',
    ),
) );
|improve this answer|||||
  • Thanks @fischi - could I kindly ask u for a tip on yet another modification to this query: what if I need to get all posts WHERE state is 'Wisconsin' OR timezone is 'central' ORDER BY population DESC – dkatwp Feb 24 '16 at 12:01
  • see updated answer – fischi Feb 24 '16 at 13:04
  • Thanks @fischi - but I have two problems with that solution: 1) the value of 'state_clause' in meta_query array gets overwritten - so only last declaration stays ('timezone') if u actually dump the query. 2) the 'relation' => 'OR' ruins the logic of a query - now result is all posts in DB as population exists in all cases – dkatwp Feb 24 '16 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.