4

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.

7

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.

|improve this answer|||||
  • I improved the code, see now if works for you – Cesar Henrique Damascena Jul 2 '17 at 23:52
  • Yes mate, I was about to wright an answer saying that I've put the post_date first in your code and it worked, but you changed your answer first. Yes, it worked. Thank you very much! – drabello Jul 2 '17 at 23:57
  • I'm glad it worked for you :D, if you can please mark as the correct answer or post your answer please, it will help other people with the same question, thanks! – Cesar Henrique Damascena Jul 3 '17 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.