How to alter the Query in a Post Type Archive – WordPress

Change the posts order in a Custom Post Type Archive page

I had created a file for my Books custom post type in order to show the archive. I had followed the WordPress way (more on that here) instead of coding a loop and pagination myself.

  • File: archive-books.php

Now I needed to change the order, the client wanted to show the post alphabetically. Using the pre_get_posts action you can alter the query.

Here's the snippet you'd have to put in your functions.php file. Notice the conditional tag is_post_type_archive('books')

function my_alter_archive( $query ) {

if ( is_post_type_archive('books') ) {
        set_query_var( 'orderby', 'title' );
        set_query_var( 'order', 'ASC' );
    }
}
add_action( "pre_get_posts", "my_alter_archive" )

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*