wp_reset_query()WP 2.3.0

Invalidates (destroys) the data of the last query created for use in an arbitrary WordPress Loop and restores the default loop data.

An arbitrary query (WordPress Loop) is performed by query_posts() function, which overwrites the global variable $wp_query.

This should be used after query_posts() or if $posts or $wp_query variables have been used in the code. This will remove obscure bugs that occur when default WP_Query object was overwritten.

The function should be called immediately after an arbitrary loop and needs to all conditional tags work correctly and global variables correspond to the current page (query).

1 time — 0.000022 sec (very fast) | 50000 times — 0.04 sec (speed of light)

No Hooks.

Return

null. Nothing.

Usage

wp_reset_query();

Examples

0

#1 Query data reset after a Custom Loop

This example shows how to use the function after a custom loop. Note that the loop in the example is probably being used in addition to the main loop.

<?php

query_posts( [ 'post_parent' => 5 ] );

if ( have_posts() ):
	while ( have_posts() ) :
		the_post();

		// Do stuff with the post content.
		the_title();
		the_permalink(); // Etc.

	endwhile;
else:
	// Insert any content or load a template for no posts found.
endif;

wp_reset_query();

?>

query_posts() will change your main query and it can be a huge problem. Only use query_posts() if absolutely necessary. Creating a new instance of WP_Query or get_posts() is much better way for secondary loops. If you would like to modify the main query, use the pre_get_posts action. Be sure to put your pre_get_posts filter in your functions.php file.

Notes

  • Global. WP_Query. $wp_query WordPress Query object.
  • Global. WP_Query. $wp_the_query Copy of the global WP_Query instance created during wp_reset_query().

Changelog

Since 2.3.0 Introduced.

Code of wp_reset_query() WP 5.9.3

function wp_reset_query() {
	$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
	wp_reset_postdata();
}