Displaying posts from all categories on an archive page

In WordPress the “Blog” page is what displays all the posts from different categories. You can only have 1 blog page and it can either be on the front page or some other specified page. It can be configured from WordPress admin dashboard -> Appearance -> Reading -> Your homepage displays -> Posts page.

With a filter in your child theme’s functions.php file it’s possible to modify the WordPress main query to do something similar to a blog page on a different archive page.

Let’s say you were to create a category called “All” and you would like it to display posts from all categories. When you create a category from WordPress admin dashboard -> Posts -> Categories it gets assigned a slug (in this case all) and a path where you can browse the archives of this category which you can navigate to by clicking on View (the path would depend on your permalink settings, such as /category/all).

The following code can achieve that by removing the category name from the query:

PHP
add_filter('pre_get_posts', function($query) {
    if($query->is_main_query() && $query->is_category('all')) {
        $query->set('category_name', '');
    }
    return $query;
});

The code only applies to the main query when the query is for the “All” category. It then unsets the category name resulting in posts from all available categories.

Along with unsetting the category name, you could also modify the query further such as including custom post types:

PHP
$query->set('post_type', ['post', 'custom_post_type']);

or anything else WP_Query supports.

Leave a comment

Your email address will not be published. Required fields are marked *