→ How to Customize WordPress Archive Queries

An archive page is a listing of similar posts. They’re usually posts grouped by category, but they can also be grouped by tag, post type, author, date, etc.

By default, WordPress sorts archive posts in descending order (newest first). It also uses the Blog pages show at most setting (within Settings >Reading) to determine how many posts to show per page.

What if we want to sort archives in a different way, or modify other parts of the query?

Modifying the Query

I often see developers using a custom WP_Query in archive templates. The downside of this approach is that the database is getting queried twice, adding unnecessary overhead. It also breaks other plugins that rely on WP’s default archive query.

Instead of creating an entirely separate query, we recommend using WP’s pre_get_posts filter to modify the existing query.

In this first example, we want to show 20 posts per page for all Category archive pages.

<?php
function fwp_archive_per_page( $query ) {
    if ( is_tax( 'category' ) ) {
        $query->set( 'posts_per_page', 20 );
    }
}
add_filter( 'pre_get_posts', 'fwp_archive_per_page' );

Next, we’ll modify the blog index to include both Posts and Products, and sort by title.

<?php
function fwp_home_custom_query( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'product' ) );
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
}
add_filter( 'pre_get_posts', 'fwp_home_custom_query' );

IMPORTANT: Notice how we’re using conditionals like $query->is_home().

Without using conditionals, these changes would apply to ALL WordPress queries, causing undesired results!