Sort posts by Date (DESC) and by Title (ASC)

Currently, the posts of my website are ordered alphabetically by title:

/* Order Posts Alphabetically */
function prefix_modify_query_order( $query ) {
  if ( is_main_query() ) {
    $query->set( 'orderby', 'title' );
    $query->set( 'order', 'ASC' );
  }
}
add_action( 'pre_get_posts', 'prefix_modify_query_order' );

Now, I want to sort the posts alphabetically by title (ascending), but also by date (descending).

Like this example:

  • AUDI A1 Ambition 1.4 (posted in 01/01/17)
  • AUDI A1 Ambition 1.4 (posted in 01/01/16)
  • AUDI A1 Ambition 1.4 (posted in 01/01/15)
  • BMW 120i Active Flex 2.0 (posted in 01/01/17)
  • BMW 120i Active Flex 2.0 (posted in 01/01/16)
  • BMW 120i Active Flex 2.0 (posted in 01/01/15)
  • Citroen…

Changing the orderby parameter to $query->set( 'orderby', 'date title' ); does not resolve my problem because I need to show the most recent posts first.

I would appreciate any other ideas.

1
1

You can pass an array to the query as the following example described in the Codex shows:

$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);

$query = new WP_Query( $args );

In your case will be something like this:

/* Order Posts Alphabetically */
function prefix_modify_query_order( $query ) {
  if ( is_main_query() ) {

    $args =  array( 'post_date' => 'DESC', 'title' => 'ASC' );

    $query->set( 'orderby', $args );
  }
}
add_action( 'pre_get_posts', 'prefix_modify_query_order' );

If you want the post_date as the primary filter, you have to change his position in the array, now the code will query all the posts alphabetically starting by the newest post_date.

Leave a Comment