Themes

Include Sticky Posts in Page Post Count on the Home Page

Developers of different WordPress themes often use special styles for the home page, and if you want everything look good, you need to display a certain number of posts. But when you add sticky posts the number of posts on the home page changes. As per example, if posts per page is set to 5, and there are 2 sticky posts, you only want 3 posts from the main query, and not the 5 set as the site’s default.

So what do we do?


// Include Sticky Posts in Page Post Count 
add_action( 'pre_get_posts', function( $query )
{
    if ( $query->is_home && $query->is_main_query() )
    {
        $posts_per_page = get_option( 'posts_per_page' );
        $sticky_posts 	= get_option( 'sticky_posts' );

        // if we have any sticky posts and we are at the first page
        if ( is_array($sticky_posts) && !$query->is_paged() )
        {
            $sticky_count = count($sticky_posts);

            if ( $sticky_count < $posts_per_page )
            {
                $query->set('posts_per_page', $posts_per_page - $sticky_count);
            }
            else
            {
                $query->set('posts_per_page', 1);
            }
        }
    }
});
Just paste this code into the functions.php file your theme.

Leave a comment