分类列表分页

WordPress single post custom query pagination jump back to the first page of the problem

When developing custom queries on WordPress single post pages, if paging is required, we will most likely find that the page will automatically jump to the first page when clicking on the second or third page. This problem is rather insidious, and beginners who are not familiar with WordPress development may not know where to start to troubleshoot. Below we analyze the reasons for this problem and provide you with sample code to solve this problem.

In WordPress, we know that post list and single post page can be paged, the paging parameter name of these two pages is different, the paging parameter name of post list is "paged", and the paging parameter name of single post page is "page". Most of the paging functions tend to use "paged" as the paging parameter name, which leads to the user clicking on the second page, the system can not get the required page number in the query, it will return the default first page.

Sample code for solving single article page without paged pagination parameters

Know the reason for the problem, the solution is obvious, we just need to implement custom article query single article page, add a "paged" paging parameters, and paging parameters "page" value assigned to "paged", WordPress will be able to get the current page, get the corresponding page number of the page. Sample code is as follows:

add_action('template_redirect', function ()
{
    if (is_singular('company')) {
        global $wp_query;
        $page = (int)$wp_query->get('page');

        if ($page > 1) {
            // Convert 'page' to 'paged'.
            $wp_query->set('page', 1);
            $wp_query->set('paged', $page);
        }

        // Remove the Hook that standardizes on the site to prevent jumps
        remove_action('template_redirect', 'redirect_canonical');
    }
}, 0);

Add the above code to the functions.php of your WordPress theme and the problem is solved.

Modify the paging function to achieve a single article page paging problem approach

To put it another way, since this problem is caused by the default use of the "paged" parameter name in the paging function, is it possible to solve the problem by modifying the paging function to use the "page" parameter to generate a paging link in the but article page? I think it should be possible. The specific code is left to you to realize it.

Related Posts

Leave a Reply

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