Multiple Loops in WordPress

Posted on April 23rd, 2011

When coding complex WordPress pages with more than one loop, it can happen that one of the loops doesn’t behave as expected. with a bit of knowledge and a very useful function, we can avoid this.
The following example features two distinct loops. Notice the rewind_posts() function on line 8. This example can be used on any WordPress file as is: index.php, single.php, etc.

// First loop (get the last 3 posts in the "featured" category)

<?php query_posts('category_name=featured&showposts=3'); ?>

<?php while (have_posts()) : the_post(); ?>

<!-- Do stuff... -->

<?php endwhile;?>
 

//loop reset

<?php rewind_posts(); ?>

//Second loop (Get all posts)

<?php while (have_posts()) : the_post(); ?>

<!-- Do stuff... -->

<?php endwhile; ?>

Code explanation.

This piece of code doesn’t use any hacks; rewind_posts() is a standard WordPress function.

The purpose of rewind_posts() is to “clear” a loop that has been previously used (like the first loop in our example above), allowing you to use a second loop that isn’t affected by the first loop’s results.