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 Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. 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',
),
// ...
See #31045 for more background.
We’ve also done a sweep through WP’s primary query classes – WP_Query
, WP_User_Query
, and WP_Comment_Query
– to ensure that ‘orderby’ can be used in the same way everywhere. As of 4.2, ‘orderby’ syntax – including multidimensional arrays, ‘meta_value_num’, and the meta query index references described above – is the same in each of these three query classes. See #31265.
#4-2, #dev-notes, #post-meta, #query