Why does this loop only work on the homepage?

I’ve been trying to figure this out all day now.

Consider the following code below:

<div class="slider">
    <div class="slides"><?php
       wp_reset_query();
         if(have_posts()) : 
           while (have_posts()) : 
             the_post();
             if(is_sticky()) : ?>
               <div class="slide"><a rel="bookmark" href="https://wordpress.stackexchange.com/questions/92193/<?php the_permalink() ?>"><?php echo the_post_thumbnail('full'); ?><h2><?php the_title(); ?></h2></a></div>
             <?php endif;
           endwhile; 
         else: ?>
           <p>Sorry, no posts matched your criteria.</p>
         <?php endif; ?>
      <div class="left-arrow"></div>
      <div class="right-arrow"></div>
  </div>
</div>

The loop above doesn’t work on the site’s pages (e.g: page 2/3/4) or 404.php, but works perfectly fine on page 1 (the index.php).

Why is that and how do I fix this?

2 Answers
2

If you look at that code carefully, the only thing it ever prints are sticky posts:

if(is_sticky()) : ?>
   <div class="slide"><a rel="bookmark" href="https://wordpress.stackexchange.com/questions/92193/<?php the_permalink() ?>"><?php echo the_post_thumbnail('full'); ?><h2><?php the_title(); ?></h2></a></div>
<?php endif;

You stand a better chance of having sticky posts on page 1 of the index than on any page thereafter. 404 pages don’t have posts at all, sticky or not. That is why they are 404 pages.

I think that is why the code appears not to work on some pages, but it isn’t that the code is broken, just that the conditions for printing post data and not met.

Leave a Comment