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() ) { $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.
Related posts:
- Get WordPress comments outside of WordPress
- A Better Tag Cloud
- How to add support for navigation menus to your WordPress theme