11

How can I set multiple meta keys order by meta value, can any one give me some example?

closed as unclear what you're asking by TheDeadMedic, cjbj, kaiser Nov 16 '16 at 10:23

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    Welcome to WPSE - for us to help you, you need to help us. Can you describe in more detail what you are trying to do, and perhaps post some code samples. – TheDeadMedic Nov 16 '16 at 9:44
26

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.

  • do not forget to add the type of the meta key/value. it will affect the results. by default wp will treat your meta as a string. – Alexander Ivashchenko Dec 12 '18 at 11:54
  • But what if I don't want to only return results where the state is Wisconsin? I want all states to be returned and and I want rows where there may or may not be a city and still order by those 2 fields. e.g. no WHERE clause at all - just an ORDER BY. – Felix Eve May 9 at 9:40

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