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.

2 comments

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

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo