Add multiple order options to the query

You can add multiple orderby columns to the WP_Query arguments, but WP_Query doesn’t support adding different order options (DESC,ASC) to each value of the orderby argument (or I can’t seem to find it).

In order to do this you will have to use the posts_orderby filter.

1
2
3
4
5
6
7
 
$args = array(......
	      'orderby'        => 'post_title comment_count', 
	      'order'          => 'ASC', 
	      .....
	       );
new WP_Query( $args );

This would generate in your query the following:

 
SELECT .... FROM ..... ORDER BY post_title ASC, comment_count ASC

But if what we want is

 
SELECT .... FROM ..... ORDER BY post_title ASC, comment_count DESC

we would use the post_orderby filter like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
function my_new_order_option($orderby) {
 
  global $wpdb;
  $order  = $wpdb->posts . '.post_title ASC, ';
  $order .= $wpdb->posts . '.comment_count DESC';
 
  return $order;
} 
 
add_filter( 'posts_orderby', 'my_new_order_option' ); 	
 
$query = new WP_Query( $args );
 
remove_filter( 'posts_orderby', 'my_new_order_option' );