WP 4.0: WP_Query: fixes in the orderby parameter

In WordPress 4.0, issues related to sorting query results with WP_Query have been fixed, especially when sorting by multiple columns simultaneously.

The sorting when retrieving results in WP_Query is determined by the orderby and order parameters, which are responsible for the ORDER BY clause in the SQL query. By default, orderby = post_date and order = DESC. DESC (descending) means that the results are sorted by the post_date column in reverse order (latest posts first).

The orderby parameter specifies a string - the name of the column to sort by:

$query = new WP_Query( [ 'orderby' => 'post_title' ] );

// or you can use the alias (synonym) for post_title, which is title:
$query = new WP_Query( [ 'orderby' => 'title' ] );

As a result of such a query, the SQL condition responsible for sorting will look like this:

ORDER BY post_title DESC

Sorting order for each column

In the orderby parameter, you can also specify two columns for sorting, separated by a space. Then the result will be sorted by two columns sequentially:

$query = new WP_Query( [ 'orderby' => 'title author' ] );

The SQL will look like this:

ORDER BY post_title, post_author DESC

Such a query will return an unexpected result. This is because in this query, the sorting order DESC is specified only for the second column, and for the first column, it is ASC. This is because by default in MySQL, columns are sorted in ascending order - from smallest to largest - ASC (ascending).

In WP 4.0, the error has been fixed, and the sorting order is set for all specified columns, i.e.:

$query = new WP_Query( [ 'orderby' => 'title author' ] );

will return:

ORDER BY post_title DESC, post_author DESC

Also, in WP 4.0, it became possible to specify the sorting order for each column separately. For this, in the orderby parameter, you need to pass an array with the following syntax:

$query = new WP_Query( [
	'orderby' => [ 'title' => 'DESC', 'menu_order' => 'ASC' ]
] );

As a result, the SQL will be like this:

ORDER BY post_title DESC, menu_order ASC

For more details on how the ORDER BY query is constructed, refer to the methods WP_Query::parse_order() and WP_Query::parse_orderby().