1

I am using the same template for author.php and home/blog.php.

I have a loop split into 3 parts.

<?php

if(have_posts()): the_post;
  //do a thing
endif:

$i = 0;
while(have_posts()): the_post();
  //do three things
$i++; if ($i == 3): break; endif; 
endwhile;

while(have_posts()): the_post();
  //do the rest
endwhile;

?>

This seems to be working fine on the home/blog page but on the author.php, in the 2nd while loop, I'm getting posts starting from 1, when I shouldn't be getting any.

For this particular author I have 2 posts so I should be getting something like:

<?php

if(have_posts()): the_post();
  //post1
endif:

$i = 0;
while(have_posts()): the_post();
  //post2
$i++; if ($i == 3): break; endif; 
endwhile;

while(have_posts()): the_post();
  //no posts
endwhile;

?> 

But instead I'm getting:

<?php

if(have_posts()): the_post();
  //post1
endif:

$i = 0;
while(have_posts()): the_post();
  //post2
$i++; if ($i == 3): break; endif; 
endwhile;

while(have_posts()): the_post();
  //post1 + post2
endwhile;

?>

What's up with my loops?

1 Answer 1

3

When the loop is complete, have_posts() rewinds it back by calling the rewind_posts() method of the $wp_query object, see here.

Here's another (more simple?) setup that you could try:

while( have_posts()): the_post();
   if ( 0 == $wp_query->current_post ): 
       // post 1   
   elseif ( 1 == $wp_query->current_post ): 
       // post 2      
   else:        
       // other posts   
   endif;
endwhile;
wp_reset_postdata();

where we use the current_post property of the global $wp_query object to keep the track of the current post.

3
  • It's difficult to see how this would work in my context. I have 3 sections, and I believe I need to come out of the loop because I don't that content repeating with every post. So I would need an endif; inbetween each statement?
    – UzumakiDev
    Jul 7, 2014 at 11:38
  • If you must use the above setup, you can for example check the post count $wp_query->post_count before entering the while loops.
    – birgire
    Jul 7, 2014 at 13:12
  • 1
    your rewind explanation helped me find a fix that I could understand :) <?php if(in_array($post->ID, $do_not_duplicate)) continue; ?> it's messy I know.
    – UzumakiDev
    Jul 7, 2014 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.