Nested loops with WP_Query

I struggled with this for a while and then realised the post object of the current query needs to be saved to a temporary variable [$save_original_post_object = $post;] so it can be restored after the nested loop is finished [$post = $save_original_post_object;]. Additionally you need to setup a new post object in the nested loop [$term_query->the_post();].

$save_original_post_object = $post;
$term_query = new WP_Query($args);
if($term_query->have_posts()) :
	while($term_query->have_posts()) :
		$term_query->the_post();
		echo '<h1 class="post_title"><a href="'.get_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a></h1>';
	endwhile;
else:
endif;
wp_reset_postdata();
$post = $save_original_post_object;

Revisions

Tags: ,

No comments yet.

Leave a Reply