I am literally clueless as to why the code does not function properly on the first page, but functions as expected on the second page. The second query should return the latest 3 posts in the pagination loop, yet it also returns posts from the first query. Instead of 3 posts on the homepage, there are 6, but on the second page, you see the expected 3.
My code is below:
<section id="main" class="c6" role="main">
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
<header>
<h2>Featured Posts</h2>
<div class="slider">
<div class="slides">
<?php wp_reset_query(); ?>
<?php $sticky_query = new WP_Query('nopaging=true'); ?>
<?php if(have_posts()) : while ($sticky_query->have_posts()) : $sticky_query->the_post(); ?>
<?php if(is_sticky()) : ?>
<div class="slide"><a rel="bookmark" href="<?php the_permalink(); ?>"><?php echo the_post_thumbnail('full'); ?><h2><?php the_title(); ?></h2></a></div>
<?php endif; ?>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<div class="left-arrow"></div>
<div class="right-arrow"></div>
</div>
</div>
</header>
<footer>
<h3>The New Stuff</h3>
<ul>
<?php wp_reset_query(); ?>
<?php query_posts('showposts=3&paged='.$paged); ?>
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<div class="clearfix"><li>
<h4><a rel="bookmark" href="<?php the_permalink(); ?>">
<?php echo the_post_thumbnail('full'); ?>
<span><?php the_title(); ?></span>
</a></h4>
<?php the_excerpt(); ?>
</li></div>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
</footer>
</section>
Am I doing something wrong, or would this be the expected output?
I see a number of issues, aside from the use of query_posts ( this should raise immediate alarm bells ). I strongly recommend you don’t use the alt syntax, and that you minimise the unnecessary opening and closing PHP tags as it obscures your code.
Here is a cleaned up version of your first query loop:
You can immediately see that your first check is if the main query has posts, not your sticky query, the main query.
You then immediatley follow this with a
query_posts
loop, here is a cleaned up version:Immediatley you call
wp_reset_query
, despite not having a query to clean up. This makes no sense.Then you go on to do a query_posts call. As mentioned earlier, this is incredibly bad practice. Never use query_posts. Instead consider using WP_Query as you did earlier.
So to summarise:
I see potential bug here:
Did you mean
if($sticky_query->have_posts())
?EDIT
Also, as Tom J Nowell mentioned, you have that
wp_reset_query()
, which, I guessed, can’t do anything, because you have nothing to reset. BUT! You are usingquery_var
paged
, so, you are maybe resetting that var too, which changes your sub-queries. Remove that definitely.