Include sticky posts in ‘Blog pages show at most’ X number of posts?

I’m using the default Loop Code.

I’ve set the ‘Blog pages show at most’ option in Settings > Reading to 11.

In my home page -set to show Latest Posts- whenever I mark a post as ‘Sticky’ it’s being added to the original ‘Blog pages show at most’ count, so the home page now shows 12 posts instead of 11.

I want to avoid this!

I want to keep 11 posts in total, that being -in the example above- 1 Sticky post plus 10 normal posts. Is this possible?

I’ve already tested this with default themes and all plugins turned off.

EDIT

So far I’ve found that I could modify the main query using pre_get_posts.

What I intend to do then is query for only the sticky posts, and then merge that query with the main query.

I found this snippet but I’m having problems converting that into a pre_get_posts working function.

$newsposts = array();

$sticky = get_option('sticky_posts');
$args = array(
    'post__in' => $sticky,
    'posts_per_page' => $num
);
$sticky_posts = get_posts($args);

if( count($sticky_posts) < $num ) {
    $extras = $num - count($sticky_posts);
    $args= array(
    'post__not_in' => $sticky,
    'posts_per_page' => $extras
);
$extra_posts = get_posts($args);
$newsposts = array_merge($sticky_posts, $extra_posts);
}
else $newsposts = $sticky_posts;

1 Answer
1

You can use this code:

add_action( 'pre_get_posts', 'exclude_sticky' );

function exclude_sticky( $query ) {
    if ($query->get('paged') == 0) {
        $sticky = get_option('sticky_posts');
        $num = get_option('posts_per_page');
        $extras = $num - count($sticky);
        $query->set( 'posts_per_page', $extras );
    }

}

Leave a Comment