Fixing WordPress Custom Query Pagination Redirecting to First Page on Single Posts

When developing custom queries on a single WordPress post page (singular), you might encounter a frustrating issue: clicking on page 2 or page 3 of your paginated results automatically redirects you back to the first page. This problem is subtle and can be quite a headache for developers who aren’t familiar with WordPress’s internal routing logic. In this article, we’ll analyze why this happens and provide clean code solutions to fix it.

The Cause: ‘paged’ vs ‘page’

In WordPress, both archive lists and single post pages support pagination, but they use different parameter names in the background. Archive pages (categories, tags, etc.) use the paged parameter to track the current page number. However, single post pages (singular) use the page parameter for their internal pagination (e.g., when you use the <!--nextpage--> tag).

Most pagination functions and query libraries defaults to looking for the paged parameter. When you click a pagination link on a single post, the system often can’t find the expected page number in the query, causing it to fall back to the default first page.

Solution 1: Mapping ‘page’ to ‘paged’

The simplest way to resolve this is to intercept the request and manually assign the value of the page parameter to the paged parameter before WordPress processes the query. You also need to disable the canonical redirect for those specific requests to prevent WordPress from “correcting” the URL back to page 1.

add_action('template_redirect', function () {
    if (is_singular('company')) { // Replace 'company' with your post type
        global $wp_query;
        $page = (int)$wp_query->get('page');

        if ($page > 1) {
            // Convert 'page' to 'paged' for the custom query
            $wp_query->set('page', 1);
            $wp_query->set('paged', $page);
        }
        
        // Remove the canonical redirect to prevent jumping back to page 1
        remove_action('template_redirect', 'redirect_canonical');
    }
}, 0);

Add this code to your theme’s functions.php file. Replace 'company' with your actual post type slug (or use is_single() for standard posts).

Solution 2: Modifying the Pagination Function

An alternative approach is to modify your pagination output logic. Instead of relying on the default behavior, you can explicitly tell your pagination function to use the page parameter when generating links for single post pages. This keeps the URL structure consistent with what WordPress expects for single posts and avoids the need for redirects.

By understanding these underlying mechanics, you can ensure that your custom data displays work perfectly across all sections of your WordPress site, providing a smooth and predictable user experience.

Related Posts

Leave a Reply

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