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.

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

Modifying the query

We 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.

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.

function fwp_home_custom_query( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', [ 'post', 'product' ] );
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
add_filter( 'pre_get_posts', 'fwp_home_custom_query' );

See also