WordPress 4.2 is coming soon, and Boone Gorges writes on Make WordPress Core about WP_Query improvements for ‘orderby’ and ‘meta_query’:
WP 4.2 will include a number of improvements in the way query classes handle ‘orderby’, particularly when used in connection with the ‘meta_query’ parameter.
WP_Query has long supported the sorting of results by postmeta, using the following syntaxes:
$q1 = new WP_Query( array( 'meta_key' => 'foo', 'orderby' => 'meta_value', ) ); $q2 = new WP_Query( array( 'meta_key' => 'foo', 'orderby' => 'foo', ) );
These arguments have always operated more or less independently from ‘meta_query’. Internally, ‘meta_key’ and ‘meta_value’ are converted to the first clause in a ‘meta_query’, but this conversion is opaque as far as ‘orderby’ is concerned.
WP 4.2 will address this shortcoming with a new syntax for ordering by specific clauses of a ‘meta_query’ array. When building the meta_query’ parameter, use explicit array indexes for the meta query clauses. These indexes will be used as handles, which can be referenced from the ‘orderby’ param. For example:
$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. ) );
This new syntax can be used in conjunction with complex ‘orderby’ parameters:
// ... 'orderby' => array( 'city_clause' => 'ASC', 'state_clause' => 'DESC', ), // ...
Read more at Make WordPress Core.