Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
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 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 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 at 13:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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