The Loop is the heart of Wordpress. Creating multiple loops is the way to go if you want to display your content in inspiring and novel ways. Featured posts, portfolio listings, different styled categories, they are all created using multiple Wordpress Loops.

The Loop is the heart of Wordpress. It displays all the posts, categories, tags and archives.

Now the question is “why do we need multiple loops?

Basically you might want to do something with one group of posts and then do something different to another group of posts, yet still display them both on the same page. While this is somewhat cryptic here are some practical examples of loops that you might want to implement into your Wordpress theme:

  • List your featured posts. This can be done by listing posts in a particular category or tagged with a particular tag.
  • Have a category “videos” that you might also want displayed on the home page along side your main articles.
  • Display a carousel with your portfolio above your main content.
  • Display your posts using multiple loops and multiple columns.
  • Create an Asides area on your blog

As always, besides the benefits there are also limitations and drawbacks to multiple loops:

  • You can only have navigation for the main loop
  • If you reset the main loop to allow for the other loops to work correctly you will loose the archive navigation
  • You’ll have to create your own custom query

We’ll start with the basic loop:

     <?php if (have_posts()) : ?>
               <?php while (have_posts()) : the_post(); ?>
     <!-- do stuff ... -->
     <?php endwhile; ?>

Now the key to using multiple loops is that $wp_query can only be called once. In order to get around this it is possible to re-use the query by calling rewind_posts() or by creating a new query object.

Using rewind_posts()

In order to loop through the same query a second time, call rewind_posts(). This will reset the loop counter and allow you to do another loop.

  <?php rewind_posts(); ?>

  <?php while (have_posts()) : the_post(); ?>
    <!-- Do stuff... -->
  <?php endwhile; ?>

This isn’t particularly useful but if you ever need it, it’s there for you to use!

List posts in a “featured” category with query_posts()

Now we start building something useful.

  // Get the last 3 posts in the featured category.
  <?php query_posts('category_name=featured&showposts=3'); ?>

  <?php while (have_posts()) : the_post(); ?>
    <!-- Do featured stuff... -->
  <?php endwhile;?>

//We reset the loop
  <?php rewind_posts(); ?>

//We build the normal loop that will list out blog posts
  <?php while (have_posts()) : the_post(); ?>
    <!-- Do stuff... -->
  <?php endwhile; ?>

There is a rather annoying problem with this code. In case we want to use pagination for the normal loop that displays the blog posts, when we click ‘previous’ page 2 will display the same posts as on the homepage. The reason behind this is the rewind_posts(); function. Since it resets the loop we’ll display the first posts every time!

Next let’s see how we can make use of the navigation.

Create a new query object.

If you need to keep the original query around, you can create a new query object. This will also allow us to make proper use of our navigation!

<?php $my_query = new WP_Query('category_name=featured&showposts=3'); ?>

<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
  <!-- Do special_cat stuff... -->
<?php endwhile; ?>

The query object my_query is used because you cannot use the global have_posts() and the_post() since they both use $wp_query. Instead, call into your new $my_query object.

Store your query for future use

Another version of using multiple Loops takes a different approach to getting around the inability to use have_posts() and the_post(). To solve this, you need to store the original query in a variable, then re-assign it when with the other Loop. This way, you can use all the standard functions that rely on all the globals.

This piece of code will work on php5 servers only.

 // saving the query
 <?php $temp_query = clone $wp_query; ?>
 <!-- Do stuff... -->  

 //listing out featured articles
 <?php query_posts('category_name=featured&showposts=3'); ?>

 <?php while (have_posts()) : the_post(); ?>
   <!-- Do special_cat stuff... -->
 <?php endwhile; ?>

 // restoring the query so it can be later used to display our posts
 <?php $wp_query = clone $temp_query; ?>

More!

If you liked this and want to learn more loop tricks for Wordpress here are some links for you:

 

Related Posts

No related posts.
 

20 Comments

  1. Posted July 9, 2009 at 4:53 pm | Permalink

    Great post Cristian! I already enjoyed your previous post and now I’m loving this one.
    Your writings fits very well with Jean’s. You guys are making a great team!

  2. Posted July 9, 2009 at 5:46 pm | Permalink

    Very nice post, the loop is something I’ve been wanting to learn more about.

  3. Posted July 9, 2009 at 5:52 pm | Permalink

    @TechAdmin Thanks! Will try and keep up the good work!

  4. Posted July 9, 2009 at 7:45 pm | Permalink

    Excellent post! I absolutely love WordPress and there really are so many things you can do with the loop.

  5. Posted July 9, 2009 at 11:23 pm | Permalink

    Excellent post! I’m a WordPress fan and I totally agree with you: loops help you do a lot of things! Keep up sharing with us such good posts!

  6. Posted July 10, 2009 at 5:18 am | Permalink

    This is an awesome tutorial. I was dealing with multiple loops in the past when I realized pagination would always break. I never really thought of doing a clone of $wp_query. Just to be clear on somethings here.

    Using the stored query method, I would store the original query in $temp_query which displays my post. Then I would do my custom query which is to list a number of posts from a certain category which I assume does not need any pagination. To round it all up, I would set the $wp_query to $temp_query which was my original query.

    In other words, this would only work if there is no pagination on the first query? What if I want to add pagination for my custom queries too? Maybe you could shed some light on that?

  7. Posted July 10, 2009 at 9:59 am | Permalink

    Thanks for this interesting tutorial

  8. Posted July 10, 2009 at 2:20 pm | Permalink

    Well explained mate thanks very much, i wasnt even aware wordpress did this

  9. Posted July 10, 2009 at 3:28 pm | Permalink

    I’ve got it dear, but can i use more than two loops at my Home page ? Because most modern themes and all “magazine” themes display at least two loops on the blog’s home page; these can be used, for example, for a “featured posts” section. While using two loops is very easy to do, preventing duplicate posts from displaying is not… until, that is, you learn this easy method of preventing them.

    I want to share two loops
    1)

    and second one

    2)

    $ids));
    while (have_posts()) : the_post();
    the_title();
    the_content();
    endwhile;
    ?>

    Here, the first loop starts with the very useful query_posts() function, which allows you to specify a wide range of parameters to be used by the loop. The showposts parameter allows you to get the specified number of posts. Just before the loop starts, I create a PHP array named $ids, which will receive all IDs of the posts returned by this loop.

    Like the first one, the second loop uses the query_posts() function with the post__not_in parameter. This parameter allows you to specify a list of posts that you don’t want to be displayed, in the form of a PHP array. As you probably saw, I passed the $ids array to t

  10. Posted July 11, 2009 at 3:41 am | Permalink

    Wow, it’s nice to have that step by step walk through. Very comprehensive and useful little reference.

  11. Posted July 11, 2009 at 8:09 pm | Permalink

    Dang… I should have seen this earlier. I guess, rewind_posts is what I missed out last time. I was trying to add a bunch of recent posts with most comments at the end of single post (before comments) and failed miserably. Will try it again…

  12. Posted July 16, 2009 at 3:46 pm | Permalink

    these loops are really very great because by them we can do a lot of changes i know it is little bit tough but still i love it!

  13. Ed
    Posted July 18, 2009 at 6:50 am | Permalink

    Thank you very much. This was very helpful.

  14. Posted July 20, 2009 at 2:47 pm | Permalink

    You have explained the loops of WP very well. Such information is very much needed for smooth stability of your knowledge. Thanks for the great info.

  15. Posted August 10, 2009 at 7:00 pm | Permalink

    useful wp loops tutorial, thanks a lot..

  16. Posted December 29, 2009 at 10:08 am | Permalink

    great write-up. I find that I am often running multiple loops on a single page so it’s cool to get some fresh perspectives on how to do this.

  17. Andrei Matorin
    Posted January 4, 2010 at 6:10 pm | Permalink

    Thanks a bunch for the well written, straight-forward article. Was really clear for me!

  18. silvers
    Posted January 8, 2010 at 4:46 pm | Permalink

    i appreciate the effort that you put in to write the article but it is pretty much a carbon copy of the wordpress loop info on their own site.

    the main thing i don’t like about it, is that having read it, i still don’t know what the hell to do with a loop so that i can have the newest post in one style and the other others below on the same page.

    for this reason i don’t think this is a good tutorial at all. it would be better if you actually showed us what you were talking about, with the full code for the index.php so we had some idea what you mean.

    i don’t just go around giving people a hard time. but to be honest, i think this is pretty constructive criticism

  19. silvers
    Posted January 10, 2010 at 8:11 pm | Permalink

    Hi, i wrote the above the other day when i was frustrated as i couldn’t work out what to do. looking back i think i was harsh so if you would like to delete my comment and this one i am cool with that.

    thanks for the effort you put in to bringing us these tutorials.

  20. Posted January 12, 2010 at 1:43 pm | Permalink

    What about having one main loop which shows all the posts and you are supposed to show last 5 posts under each posts. I tried your example but all the posts returned the same results regardless of posts under different categories.

32 Trackbacks

  1. By pligg.com on July 9, 2009 at 11:27 pm

    Multiple WordPress Loops Explained…

    The Loop is the heart of Wordpress. Creating multiple loops is the way to go if you want to display your content in inspiring and novel ways. Featured posts, portfolio listings, different styled categories, they are all created using multiple Wordpress…

  2. [...] code comes from an article entitled Multiples WordPress loops explained, written by Cristian Antohe at Cats Who Code. If you enjoyed this article, please consider [...]

  3. By It’s About Time » links for 2009-07-10 on July 10, 2009 at 12:04 pm

    [...] Multiple WordPress Loops Explained (tags: ping.fm) [...]

  4. By links for 2009-07-10 | Links | WereWP on July 10, 2009 at 4:04 pm

    [...] Multiple WordPress Loops Explained A good tutorial to help you build multiple loops on one WordPress page. It can really be useful sometimes! (tags: WordPress tips loop tutorial) [...]

  5. [...] Wordpress: Multiple WordPress Loops Explained [...]

  6. By Weekly Wordpress Roundup 1 on July 15, 2009 at 2:29 pm

    [...] Multiple WordPress Loops Explained – “You might want to do something with one group of posts and then do something [...]

  7. By WordPress News & Notes – July 24, 2009 on July 25, 2009 at 4:51 am

    [...] post that caught my eye was ‘Multiple WordPress Loops Explained‘. I would say more, but it’s pretty self [...]

  8. [...] post that caught my eye was ‘Multiple WordPress Loops Explained‘. I would say more, but it’s pretty self [...]

  9. [...] post that caught my eye was ‘Multiple WordPress Loops Explained‘. I would say more, but it’s pretty self [...]

  10. [...] Your Facebook Status Finding a Lost WordPress Password How to Display Your Latest Twitter Entry Multiple WordPress Loops How to Get Custom Fields Outside the Loop Display Your Tags in a Drop Down Menu How to Embed CSS in [...]

  11. [...] Multiple WordPress Loops Explained – This post by Cristian Antohe at Cats Who Code explains how multiple WordPress loops work. If you’re not familiar with WordPress loops, I recommend you check out an earlier article I wrote here: The Ultimate Guide to the WordPress Loop [...]

  12. [...] Multiple WordPress Loops Explained – This post by Cristian Antohe at Cats Who Code explains how multiple WordPress loops work. If you’re not familiar with WordPress loops, I recommend you check out an earlier article I wrote here: The Ultimate Guide to the WordPress Loop [...]

  13. [...] 5. Using Multiple WordPress Loops in Your Theme [...]

  14. [...] Using Multiple WordPress Loops in Your Theme [...]

  15. [...] Your Facebook Status Finding a Lost WordPress Password How to Display Your Latest Twitter Entry Multiple WordPress Loops How to Get Custom Fields Outside the Loop Display Your Tags in a Drop Down Menu How to Embed CSS in [...]

  16. [...] Your Facebook Status Finding a Lost WordPress Password How to Display Your Latest Twitter Entry Multiple WordPress Loops How to Get Custom Fields Outside the Loop Display Your Tags in a Drop Down Menu How to Embed CSS in [...]

  17. [...] Using Multiple WordPress Loops in Your Theme [...]

  18. [...] Multiple WordPress Loops Explained [...]

  19. [...] Multiple WordPress Loops Explained – A great tutorial to get you started with multiple loops. [...]

  20. [...] 5.Using Multiple WordPress Loops in Your Theme [...]

  21. [...] Using Multiple WordPress Loops in Your Theme [...]

  22. [...] Multiple WordPress Loops Explained [...]

  23. [...] Multiple WordPress Loops Explained [...]

  24. By 10 Useful WordPress Coding Techniques « Tech7.Net on October 20, 2009 at 5:24 pm

    [...] Multiple WordPress Loops Explained [...]

  25. [...] Multiple WordPress Loops Explained [...]

  26. [...] Multiple WordPress Loops Explained [...]

  27. [...] Multiple WordPress Loops Explained [...]

  28. [...] Multiple WordPress Loops Explained – A great tutorial to get you started with multiple loops. [...]

  29. [...] Multiple WordPress Loops Explained – A great tutorial to get you started with multiple loops. [...]

  30. [...] Multiple WordPress Loops Explained – A great tutorial to get you started with multiple loops. [...]

  31. [...] Using Multiple WordPress Loops in Your Theme [...]

  32. By 65 Of The Best WordPress Tutorials « Junkiee.Net on February 21, 2010 at 9:45 am

    [...] 36. Multiple WordPress Loops Explained [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
WordPress Appliance - Powered by TurnKey Linux