I have a filtering nav bar on my posts page with “All” and some categories (“Strategy”, “Design and UX”, “Technology”, and “Company and Culture”) that alters the query using pre_get_posts to show posts belonging to those particular categories.

This is what I have in my functions.php:

function owr_blog_topic_endpoint() {
    add_rewrite_endpoint( 'topic', EP_ALL );
}
add_action( 'init', 'owr_blog_topic_endpoint' );

function owr_pre_get_posts( $query ) {
    $topic = get_query_var( 'topic' );
    if ( $query->is_home() && $query->is_main_query() && isset( $topic ) ) {
        $query->set( 'category_name', $topic );
    }
}
add_action( 'pre_get_posts', 'owr_pre_get_posts' );  

I’m showing 7 posts at a time and at the bottom of the page, I’m using the_posts_pagination() to generate the links to the pages with the rest of the posts. This works fine in the sense that it is showing the correct number of pages given the number of posts belonging to that particular category.

So, when on “All,” the URL is /notes and when a user clicks “Strategy,” for instance, the URL is /notes/topic/strategy. When we go to the second page of “All,” the URL is /notes/page/2 and doing the same from “Strategy” makes the URL /notes/topic/strategy/page/2, which is where the 404 occurs.

I have a feeling I need to add some other rewrite rules, but I’m not sure.

Edit
So, it turns out my hunch was correct and the solution is to add some rewrite rules. Here’s what I added:

function owr_blog_rewrite( $rules ) {
    return [
        'notes/topic/([^/]+)/?$' => 'topic=$matches[1]',
        'notes/topic/([^/]+)/page/([0-9]+)/?$' => 'topic=$matches[1]&paged=$matches[2]',
    ] + $rules;
}
add_filter( 'rewrite_rules_array', 'owr_blog_rewrite' );  

Everything works as expected now

1 Answer
1

So, it turns out my hunch was correct and the solution is to add some rewrite rules. Here’s what I added:

function owr_blog_rewrite( $rules ) {
    return [
        'notes/topic/([^/]+)/?$' => 'topic=$matches[1]',
        'notes/topic/([^/]+)/page/([0-9]+)/?$' => 'topic=$matches[1]&paged=$matches[2]',
    ] + $rules;
}
add_filter( 'rewrite_rules_array', 'owr_blog_rewrite' );  

Everything works as expected now

Leave a Reply

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