Multiple WordPress Loops Explained

by Cristian Antohe. 61 Comments -

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:

 

  • http://digg.com/users/techadmin TechAdmin

    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!

  • http://johndturner.com John Turner

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

  • http://www.cozmoslabs.com Cristian Antohe

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

  • http://www.joshstauffer.com Josh

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

  • http://www.sanblasvacations.com Jenny

    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!

  • Pingback: pligg.com

  • http://limetouch.com Darran

    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?

    • http://www.guitara.co.il Ben

      Any progress with that. I also really need this function, having first and second loop, but keeping the pagination.

      Cant get it… Did you have any luck with that?

  • Pingback: WordPress tip: Storing $wp_query for future use

  • http://designawardsgallery.com/ Best CSS Gallery

    Thanks for this interesting tutorial

  • Pingback: It’s About Time » links for 2009-07-10

  • http://www.highteas.co.uk Tea

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

  • http://healthylivinghelp.info Mark Slater

    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

  • Pingback: links for 2009-07-10 | Links | WereWP

  • http://www.bcvid.com Ben Cornelius Videography

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

  • http://www.dollarshower.com/about Ajith Edassery

    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…

  • Pingback: Weekly Fave’s | Eiencafe.com --> New way to graphic

  • Pingback: Weekly Wordpress Roundup 1

  • http://www.gadgetroad.com Mike

    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!

  • Ed

    Thank you very much. This was very helpful.

  • http://www.constantlyhealthy.com manuel

    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.

  • Pingback: WordPress News & Notes – July 24, 2009

  • Pingback: Wordpress Blog Services - WordPress News & Notes – July 24, 2009

  • Pingback: WordPress News & Notes – July 24, 2009 | Download E-Books Free Video Training Courses Softwares

  • Pingback: WordPress Resources - 48 Resources, Tips, Tricks & Themes | Think Design

  • Pingback: WordPress Weekend Resources - July 31, 2009 | Theme Lab

  • Pingback: Wordpress Blog Services - WordPress Weekend Resources - July 31, 2009

  • Pingback: 23+ Excellent Tutorials For WordPress Theme Developers

  • Pingback: 40+ Awesome Tutorials and Techniques For WordPress Theme Developers | tripwire magazine

  • http://www.joyoge.com/ joyoge designers’ bookmark

    useful wp loops tutorial, thanks a lot..

  • Pingback: WordPress Resources – 48 Resources, Tips, Tricks & Themes :: CSS :: WEBDESIGN FAN

  • Pingback: WordPress Resources – 48 Resources, Tips, Tricks & Themes | X Design Blog

  • Pingback: 40+ Awesome Tutorials and Techniques For WordPress Theme Developers | huibit05.com

  • Pingback: Ultimate resources wordpress development tutorials | blogfreakz.com

  • Pingback: Blog – Velagapati - 300+ Resources to Help You Become a WordPress Expert

  • Pingback: 20+ Tutorials For WordPress Theme Developers | oOrch Blog

  • Pingback: The Ultimate Wordpress Developer Toolbox | tripwire magazine

  • Pingback: 10 Useful WordPress Coding Techniques « Smashing Magazine

  • Pingback: Wordpress Blog Services - 10 Useful WordPress Coding Techniques

  • Pingback: 10 Useful WordPress Coding Techniques « Tech7.Net

  • Pingback: 10 Useful WordPress Coding Techniques | Search Engine Optimisation

  • Pingback: 10 Useful WordPress Coding Techniques – My Facebook

  • Pingback: Web Design News » 10 Useful WordPress Coding Techniques

  • Pingback: WordPress 300+ Collection of Amazing Resources | Amazing and Inspiring Design

  • Pingback: 300+ Resources to Help You Become a WordPress Expert « eBSPAD

  • Pingback: 300+ Resources to Help You Become a WordPress Expert | LeVoltz - iPhone Games, Engineering Projects, Wordpress Themes

  • Pingback: Think2free.com » 20 best tutorials and techniques to develop wordpress theme

  • http://sinthetic.net jones

    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.

  • Andrei Matorin

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

  • silvers

    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

  • silvers

    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.

  • http://www.hurricanesoftwares.com Ashish

    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.

  • Pingback: 65 Of The Best WordPress Tutorials « Junkiee.Net

  • http://www.thescube.com Shovan

    Thanks for the loop article

  • marie

    Thank you for the trick with $my_query. Helped me a lot.

  • http://www.dreamlandproduction.aw andreas Bengter

    What do I gain with following this headline and it’s instruction?

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

    I get 2 identical rows of post.. And on top of it older and newer post navigation isn’t working anymore, not on anyone of the rows of post.. I think you have to be more detailed in your description otherwise it’s isn’t of help to newbies like me.. I followed in detail so I guess even pros won’t get it to work either..

  • http://www.dreamlandproduction.aw andreas Bengter

    (so I guess it could be usefull if you could unlist/exclude the featured cathegory in the normal post.. and If you could show me how the new/older post nav could work with this..

  • Ian

    Hi,

    I found a reference to this blog post in the forum for the plugin WP Featured Content Slider on WordPress.org. Since you seem to be the expert, I was wondering if you could give me the fix for this small problem I have.

    I am only featuring pages of my WordPress site in the slider, not blog posts (not sure if that matters). Everything works great except the height of the excerpt of the text of the page that is included on the slider is higher than it should be. It goes past the navigation buttons almost to the bottom of the slider. I woud like the excerpt of the text of the page to stop above the navigation buttons so people can see them and use them. How do I fix this?

    Thanks!

  • http://www.swimmingpoolpumpsreviewed.com/ James Anders

    Wonderful article! Thanks for sharing your ideas on loops being the “heart” of WordPress. My various blogs are WordPress-based and your post is very helpful in my understanding of loops.

  • http://www.iameczemafreeforever.info Joe Blakey

    This is really great information on WordPress loops. I am actually new to using WordPress, as I am trying to build a blog for myself, and stumbling on this article has certainly been great for my personal learning experience. I’ve actually never even heard of looping as it relates to blogs, so I have definitely found this to be very enlightening. The fact that you include all of the HTML (I assume this is HTML?) is a great addition to the post as well, as it really lets me get hands on with the code. I look forward to trying and implementing this on my blog in the future.

  • Tieson Wooten

    I am a little late to the party, but thanks for the info!