Ways to Reset the Post Loop

Working within different loops different ways has it advantages …

wp_reset_query();

Used to restore the global post data to the original main query. Not necessary to use with WP_Query() or get_posts() as these do not affect the main loop.

query_posts($args); // query start

while(have_posts) : the_post(); // loop start

// loop content

endwhile; wp_reset_query(); // loop end / query reset

 

wp_reset_postdata();

WordPress Function Reference states that wp_reset_postdata(); can be used to restore the context of the template tags from a secondary query loop back to the main query loop. This affects the global $post variable.

foreach($example as $post) : setup_postdata($post); // variable defined

// some loop content

endforeach; wp_reset_postdata(); // secondary query reset

 

Temporary $post; data

As thorough as the two above methods are, when working with nested loops, and terms, they do not always restore the post data.

For this reason you can setup temporary $post data around the loop to prevent it from interfering with the parent loop.

$term_args = array(
	'orderby' => 'name',
	'order' => 'ASC'
);
						
$terms = get_terms($taxonomy,$term_args);
								
global $post;
$temp_post = $post;
										
if ($terms) {
										
        foreach( $terms as $term ) :
									
        endforeach; 
}

$post = $temp_post;

 

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.