Pagination Not working on Home Page with 2 Query

You do need to run a custom query for your second loop. You can simply adjust the main query to your needs. It is always never a good idea to run custom queries in place of the main query. One big issue is always pagination, WordPress disregards all other queries, and only focus on the main query when it comes to page functionality. I have done a quite extensive post on this, so be sure to check it out here

We can drop the second query, and just use pre_get_posts to alter the main query. Because we use offset here, we need to manually calculate pagination as we are breaking WP_Query‘s process which calculates pagination

add_action( 'pre_get_posts', function ( $q )
{
    if (    $q->is_home()       // Only target the home page
         && $q->is_main_query() // Only target the main query
    ) {
        // Get the current page number
        $current_page = get_query_var( 'paged', 1 );
        // Set offset
        $offset = 3;
        // Set posts per page
        $ppp = 2;

        if ( !$q->is_paged() ) {
            // Set page one offset
            $q->set( 'offset',         $offset );
            $q->set( 'posts_per_page', $ppp    );
        } else {
            // Handle pagination for paged pages
            $offset = $offset + ( ( $current_page - 1 ) * $ppp );
            $q->set( 'offset',         $offset );
            $q->set( 'posts_per_page', $ppp    );
        }
    }
});

You should now have your main query correctly paginated with one problem, the last page might, depending on the amount of posts, 404’ing. To adjust for that, we need to adjust the $found_posts property of the main query.

add_filter( 'found_posts', function ( $found_posts, $q ) 
{
    $offset = 3;

    if(    $q->is_home() 
        && $q->is_main_query() 
    ) {
        $found_posts = $found_posts - $offset;
    }

    return $found_posts;
}, 10, 2 );

Needless to say, your main loop on your homepage should now just be as follow

if ( have_posts() ) :
    while ( have_posts()) : 
        the_post(); 

        get_template_part( 'template-parts/content-rest', get_post_format() );

    endwhile;
    previous_posts_link();
    next_posts_link();
endif;

Leave a Comment