Fix Pagination 404 When a Custom Post Type and Page Share the Same Slug

Pagination 404 when a custom post type and a page have the same slug

When you register a post type, it is recommended to use a singular name (like the built-in post and page), but that is not always convenient. For example, we have the post type news with the slug “news”, and a News page (a normal page, not the post type archive) with the same slug. Output the news posts on this page: no problem, it works. But add pagination and open https://example.com/news/page/2/, and you get a 404. Interestingly, AJAX pagination works, and only a direct visit to the URL shows the 404.

Problem: Pagination on a page returns a 404 when a custom post type has the same slug as the page.

Solution: Add a rewrite rule that sends /slug/page/N/ to the page with the paged parameter, for every custom post type that has a page with the same slug.

Why it happens

A post type registers its own rewrite rules, for example news/([^/]+)/?$ for single posts. The URL /news/page/2/ matches this rule first, so WordPress looks for a news post with the slug “page”, does not find it and returns a 404. The page with its pagination is never reached. AJAX pagination works because it does not open this URL directly.

The fix

Get all public custom post types, check whether a page with the same slug exists, and if yes, add a rule with the top priority so it is checked before the post type rules:

<?php
add_action( 'init', 'fix_cpt_page_pagination', 20 );

function fix_cpt_page_pagination() {
    $post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );

    foreach ( $post_types as $post_type ) {
        // The URL slug can differ from the post type name.
        $slug = ! empty( $post_type->rewrite['slug'] ) ? $post_type->rewrite['slug'] : $post_type->name;

        if ( get_page_by_path( $slug ) ) {
            add_rewrite_rule(
                '^' . preg_quote( $slug ) . '/page/([0-9]+)/?$',
                'index.php?pagename=' . $slug . '&paged=$matches[1]',
                'top'
            );
        }
    }
}

The priority 20 runs the function after the post types are registered on init. After adding the code, go to Settings → Permalinks and click Save Changes, otherwise the new rule is not saved.

In the page template, take the page number from paged for your query:

<?php
$paged = max( 1, get_query_var( 'paged' ) );

$query = new WP_Query( array(
    'post_type' => 'news',
    'paged'     => $paged,
) );

NOTE: The simplest long-term fix is different slugs, for example the post type with the slug “news-item” or with has_archive instead of a separate page. Use the rule above when the URLs already exist and cannot change.

Sources:

  1. https://wordpress.stackexchange.com/questions/167461/get-list-of-registered-custom-post-types/
  2. https://wordpress.stackexchange.com/questions/135146/resolve-a-custom-post-type-name-vs-page-permalink-conflict-same-slug/