I am trying to modify the number of posts_per_page in the loop. This way:
function posts_per_page($query) {
$query->query_vars['posts_per_page'] = 3;
}
add_filter('pre_get_posts', 'posts_per_page', 11);
The problem I have is that when I do so, then sticky posts appear twice in the loop: first one at the begining of the loop and second one in their original position.
So in this case, the first page has 4 posts (3 of loop without sticky + the sticky post), and the sticky post will appear (again) later in its “page” with other 2 posts.
EDIT: SOLUTION
After doing quite much research I realised sticky posts appear always in the first page. If the original sticky post was already in the first page then only the sticky appears (this post only will appear one).
I needed to know exacty how many posts will my query have, but $wp_query->found_posts was not counting the sticky posts. And if I did $wp_query->found_posts + get_option( ‘sticky_posts’ ) wouldnt be correct as it doesnt consider the ‘sticky post from first page’ I said before and also counts non-published sticky posts.
With $wp_query->posts I get the real number of posts in my first page, so:
$sticky = count($wp_query->posts) - get_option( 'posts_per_page' );
if ($sticky<0) {$sticky=0;}//In case there is only one page of results
Now $sticky will have the real number of sticky posts.
What you describe is not an issue but normal WordPress behaviour. When you mark a post as a sticky it will be at the top of the list and it will appear in it’s original postition as well, unless the original position is on the first page. A sticky will appear at the top of the posts and in it’s original position but it will not appear twice on the same page.
You might want to do something like this:
source with minor edit: http://wpengineer.com/1719/filter-duplicate-posts-in-the-loop/
More correct would be to use the
set
method.Try that.
Note: I can’t duplicate this multiple sticky issue. If that doesn’t solve things edit your question with more detail. That may be theme specific or due to a plugin.
Consider a case where one needs the following:
It is very complex to do by setting parameters in the
pre_get_posts
hook because there is no simple way to set the number of posts for the first page. WordPress naturally sends back all sticky posts + the posts on the first page. It is not a good idea to try to calculate a new value ofposts_per_page
based on the number ofsticky posts
of the following complications.sticky posts
are less that theposts_per_page
, sometimes more, and sometimes equal. Each case will need to be dealt with separably.sticky posts
exceedsposts_per_page
as described in an answer to a similar questionTherefore the solution is to modify the code executes
the loop
.Explanation:
sticky posts
.posts_per_page
.