1

I have three loops on one page on my Wordpress website. Each loop does something different, but one of the loops (loop2) I would like to reuse at the bottom. So I try to rewind this loop right after the first time I used it, but that is not working for some reason, because the second time it won't loop again.

Has it something to do with the wp_reset_postdata I call after each loop? What am I missing?

Here is my code:

$loop1 = new WP_Query(array(
    // some args
));
if( $loop1->have_posts() ) {
    while( $loop1->have_posts() ) { $loop1->the_post();
        // do something
    }
    wp_reset_postdata();
}
$loop2 = new WP_Query(array(
    // some args
));
if( $loop2->have_posts() ) {
    while( $loop2->have_posts() ) { $loop2->the_post();
        // do something
    }
    // REWIND this loop
    $loop2->rewind_posts();
    wp_reset_postdata();
}
$loop3 = new WP_Query(array(
    //some args
));
if( $loop3->have_posts() ) {
    while( $loop3->have_posts() ) { $loop3->the_post();
        // do something
    }
    wp_reset_postdata();
}

// HERE WE GO: do the rewinded loop again
if( $loop2->have_posts() ) {
    while( $loop2->have_posts() ) { $loop2->the_post();
        echo 'Yes! It is working.';
    }
    wp_reset_postdata();
} else {
    echo 'Nope :( Not working...';
}
leendertvb
  • 86
  • 8

3 Answers3

2

Just found out it does in fact rewind the posts. There was something wrong with the loop so it didn't had any posts in it from the beginning.

To complete this question for anyone stumbling upon it in the future: actually there is no rewind_posts() necessary because the have_posts() function will already rewind the posts at the beginning of the second loop (documentation).

leendertvb
  • 86
  • 8
0

You should give a try with the rewind_posts method of WP_Query :

$loop2->rewind_posts();

See https://codex.wordpress.org/Class_Reference/WP_Query#Methods_and_Properties

vard
  • 4,057
  • 2
  • 26
  • 46
  • Thanks for your answer. Maybe I didn't make myself clear enough, but as you can see in the code, I am already doing that right after the first time I went through $loop2. Unfortunately it is not working. – leendertvb Jul 15 '15 at 15:16
  • Ah read too fast, didn't saw you already use `rewind_posts`. It's an odd thing that this is not working as excepted, I think there is some kind of conflict between `have_posts` and `rewind_posts` (`have_posts` already call `rewind_posts` itself at the end of the loop right before returning false). Can you try to comment the `rewind_posts` call to see what happen? – vard Jul 15 '15 at 15:47
  • It turned out the posts were rewinded as expected. The problem was there was something wrong with the loop so it didn't had any posts in it from the beginning. D'oh! Although, thanks for thinking with me! – leendertvb Jul 15 '15 at 19:23
0

Use wp_reset_query(); rewind_posts(); before "if(have_posts())" and after "endif;" nad use wp_reset_postdata; after each while loop completes.

Thanks