Include Sticky Post in Page Posts Count?

This is doable, and as I stated in a comment, you need to follow the following steps

  • Get a count the amount of sticky posts. This can be done by simply counting get_option( 'sticky_posts' ) which holds the ID’s of the sticky posts in the form of an array

  • You would also need to get the amount of posts per page. You don’t want to hardcode here. The amount of posts per page is stored in get_option( 'posts_per_page' ), so you are going to use this

  • The important part now is to make use of offsets to recalculate the amount of posts to show on page one from the main query. As per example in the OP, if posts per page is set to 7, and there are 4 sticky posts, we only want three posts from the main query, and not the seven set as the site’s default. From page 2 we will still need the normal 7 posts to show from the main query as we will not have sticky posts here

  • This offset will however influence the calculation of the $max_num_pages property in the main query, and what that means is, in most cases the last page will be missing. To correct this, we need to adjust the amount of posts found, basically adding our offset to the actual amount of posts found in order to correct the amount of pages. This will be done through the found_posts filter

(NOTE: This code is now tested and working)

Here is the basic idea in code:

add_action( 'pre_get_posts', function ( $q ) 
{

    if ( $q->is_main_query() && $q->is_home() ) {

        $count_stickies = count( get_option( 'sticky_posts' ) );
        $ppp = get_option( 'posts_per_page' );
        $offset = ( $count_stickies <= $ppp ) ? ( $ppp - ( $ppp - $count_stickies ) ) : $ppp;

        if (!$q->is_paged()) {
          $q->set('posts_per_page', ( $ppp - $offset ));
        } else {
          $offset = ( ($q->query_vars['paged']-1) * $ppp ) - $offset;
          $q->set('posts_per_page',$ppp);
          $q->set('offset',$offset);
        }

    }

});    

add_filter( 'found_posts', function ( $found_posts, $q ) 
{

    if( $q->is_main_query() && $q->is_home() ) {

        $count_stickies = count( get_option( 'sticky_posts' ) );
        $ppp = get_option( 'posts_per_page' );
        $offset = ( $count_stickies <= $ppp ) ? ( $ppp - ( $ppp - $count_stickies ) ) : $ppp;        

        $found_posts = $found_posts + $offset;
    }
    return $found_posts;

}, 10, 2 );     

Leave a Comment

error code: 523