Offset Post Queries without Breaking Pagination in WordPress

I thought it is an easy process when my client offered me to do that!!
But it is too much logial. It’s highly likely that you have more than one query on your blog’s home page. If that’s the case, we need to be a bit more explicit with our conditional statements. We need to make sure that the query is not only on our blog’s home page, but that we’re only targeting the main query on that page.

<?php   
/**
 *
 * Offset the main query on our blog's home page
 *
 */
function myprefix_query_offset(&$query) {

    // Before anything else, make sure this query is on our
    // blog's home page, and that it's the main query...
    if ( $query->is_home() && $query->is_main_query() ) {

        // First, define your desired offset...
        $offset = 1;

        // Next, determine how many posts per page you want (we'll use WordPress's settings)
        $ppp = get_option('posts_per_page');

        // Next, detect and handle pagination...
        if ( $query->is_paged ) {

            // Manually determine page query offset (offset + current page (minus one) x posts per page)
            $page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );

            // Apply adjust page offset
            $query->set('offset', $page_offset );

        }
        else {

            // This is the first page. Just use the offset...
            $query->set('offset',$offset);

        }

    } else {

        return;

    }
}
add_action('pre_get_posts', 'myprefix_query_offset', 1 );

/**
 *
 * Adjust the found_posts according to our offset.
 * Used for our pagination calculation.
 *
 */
function myprefix_adjust_offset_pagination($found_posts, $query) {

    // Define our offset again...
    $offset = 1;

    // Ensure we're modifying the right query object...
    if ( $query->is_home() && $query->is_main_query() ) {
        // Reduce WordPress's found_posts count by the offset... 
        return $found_posts - $offset;
    }
    return $found_posts;
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );

Happy Coding 🙂


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.