Nesting WordPress loops

Sometimes it's useful to put a WordPress loop inside another loop. To do this you'll have to create a new WP_Query object, as in this example:

<?php
   $my_query = new WP_Query( "cat=3" );
   if ( $my_query->have_posts() ) {
       while ( $my_query->have_posts() ) {
           $my_query->the_post();
           the_content();
       }
   }
   $GLOBALS['post'] =  $GLOBALS['wp_query']->post;
?>

Restoring $post is necessary because $post->comment_status of the post in the outer loop can be wrong after running the inner loop. That was the only problem I found, by I prefer to restore $post completely just to be sure. WordPress 3.0 has a function wp_reset_postdata() that you can use to restore $post.I use this technique to show an "excerpt cloud" in a post using a shortcode.

Published on May 30, 2010 at 3:01 p.m. by Nicolas and tagged development, WordPress loop, shortcode, theme, WordPress theme, WordPress, template. You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

2 comments

  1. avatar
    wrote this comment on
    Hi, one question: for what WP version is the article referred to?
    Reply to this comment
    1. avatar
      wrote this comment on
      No specific version.
      Reply to this comment

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.