WordPress at a glance

wp_reset_postdata() WP 3.0.0

Restores the global $post variable to the correct state: current post in the main query.

This function should be used every time after running an arbitrary loop (separate query). That is, in cases when the page has additional WordPress Loop in which we use global $post variable (see examples).

Put it simply: wp_reset_postdata() is needed to do not catch bugs after outputting of some non-standard posts. For example, trying to get the ID of the current post $post->ID, but get the ID of another post (not of current page). The same with the title, date, content, etc.

If you use the function wp_reset_query() to "reset data", you dont need to use wp_reset_postdata().

✈ 1 time = 0.000011s = very fast | 50000 times = 0.01s = speed of light | PHP 7.0.8, WP 4.6.1

No Hooks.

Return

Null. Nothing.

Usage

wp_reset_postdata();

Examples

#1 When to use wp_reset_postdata()?

Example showing when to use wp_reset_postdata():

<?php
$custom_query = new WP_Query('cat=-9');
while( $custom_query->have_posts() ) : 
	$custom_query->the_post();
	?>

	<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>
	</div>

	<?php
endwhile;
wp_reset_postdata(); // reset the post data
?>

#2 Example of post and page data reset

This example is completely similar to the wp_reset_query() function.

$original_query = $wp_query;

$wp_query = new WP_Query( $args );
if( have_posts() ){ 
	while( have_posts() ){
		the_post(); 
		the_title();
		the_excerpt(); 
	}
}
else
	echo 'No posts found'; 

$wp_query = $original_query;

wp_reset_postdata();

#3 Alternative

As an alternative to wp_reset_postdata() (in versions earlier than 3.0), you can first write $post to the temporary variable $tmp_post, and then after the loop return the former value of the variable $post: $post = $tmp_post:

<?php
global $post;
$tmp_post = $post; // save data
$myposts = get_posts('numberposts=5&offset=1&category=1');
foreach( $myposts as $post ) :
	setup_postdata($post);
	?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php
endforeach;
$post = $tmp_post; // return data
?>

Notes

  • Global. WP_Query. $wp_query Global WP_Query instance.

Changelog

Since 3.0.0 Introduced.

Code of wp reset postdata: wp-includes/query.php WP 5.2.2

<?php
function wp_reset_postdata() {
	global $wp_query;

	if ( isset( $wp_query ) ) {
		$wp_query->reset_postdata();
	}
}

Related Functions

From tag: reset

More from category: Queries

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register