As of WordPress 4.2, you can combine meta_query
and orderby
. The following example is taken from make.wordpress.org.
Example of a simple meta_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',
);
The orderby
parameter just includes the key of your meta_query
. You could also set it to state_clause
for a different ordering.
What’s really cool is the possibility to combine different order clauses by passing an array to orderby
:
'orderby' => array(
'city_clause' => 'ASC',
'state_clause' => 'DESC',
),
This would translate to a SQL query like
ORDER BY city_clause ASC, state_clause DESC
for more complex ordering types.