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
Reply