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:

   $my_query = new WP_Query( "cat=3" );
   if ( $my_query->have_posts() ) {
       while ( $my_query->have_posts() ) {
   $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.


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

Start a new thread

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