Skip to content

Custom WordPress Archives

Robert’s question got me thinking: WordPress gives us automatic date, author, and CPT archives, and it lets us use “rewrite rules” to set up, e.g., date-based CPT archives. So, why would I resort to a custom page template and WP_Query, when all I want, essentially, is a “copy” of WordPress’s default “blog” page, but excluding (or including) certain taxonomies (or custom post types)?

Like, if I, like Robert, wanted to exclude certain categories from my “blog” page, that’s easy:

add_action( 'pre_get_posts', function( $query ) {
    if ( $query->is_main_query() && is_home() ) {
        $query->set( 'category__not_in', array( 1 ) );
    }
} );

But setting up a “second” blog page which does cover all categories? How about that? Well, rewrite rules!

add_action( 'init', function() {
    add_rewrite_rule( '^stream/page/([0-9]{1,})/?', 'index.php?paged=$matches[1]', 'top' );
    add_rewrite_rule( '^stream/?', 'index.php', 'top' );
} );

Note: You should flush your site’s permalinks after adding this to either your functions.php or a must-use plugin. (If we were to make a true plugin out of this, we could use register_activation_hook to automatically flush permalinks.)

Except, of course, WordPress “can’t tell” the difference between this new page and the original one. Let’s tweak that earlier “post filter” just a bit:

add_action( 'pre_get_posts', function( $query ) {
    global $wp;

    if ( $query->is_main_query() && is_home() && 0 !== strpos( $wp->request, 'stream' ) ) {
        $query->set( 'category__not_in', array( 1 ) );
    }
} );

That should ensure the “filter” is no longer active on pages whose paths starts with /stream.

Replies

  1. Frank Meeuwsen on

    […] Custom WordPress Archives door Jan Boddez (jan.boddez.net) […]

    Via diggingthedigital.com, in reply to Custom WordPress Archives.

  2. Frank Meeuwsen on

    … liked this!

    Via diggingthedigital.com, in reply to Custom WordPress Archives.

  3. Robert van Bregt Robert van Bregt on

    … liked this!

    Via robertvanbregt.nl, in reply to Custom WordPress Archives.

  4. Jan Boddez Jan Boddez on

    […] turns out it is possible to move or copy WordPress “archives” without having to resort to custom page templates and all sorts of WP_Query wizardry. But, what about … […]

    Via jan.boddez.net, in reply to Custom WordPress Archives.