wp_reset_postdata()
Restores the global $post variable to the correct state: to correspond the current page.
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).
This function is needed to avoid bugs after outputting posts. Examples of possible bugs:
- Trying to get the ID of the current post (current page) through
$post->ID
, but you get the ID of another post. - Trying to get title, date, content of current page, but you get one of another page.
If you use the function wp_reset_query() to "reset data", you dont need to use this function.
No Hooks.
Return
null
. Nothing (null).
Usage
wp_reset_postdata();
Examples
#1 When to use wp_reset_postdata()?
Example showing when to use this function:
<?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 } wp_reset_postdata(); // reset the query ?>
#2 Example of reset post/page data
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 this function (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 $post variable:
<?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 } $post = $tmp_post; // return back ?>
Notes
- Global. WP_Query. $wp_query WordPress Query object.
Changelog
Since 3.0.0 | Introduced. |
wp_reset_postdata() wp reset postdata code WP 6.6.1
function wp_reset_postdata() { global $wp_query; if ( isset( $wp_query ) ) { $wp_query->reset_postdata(); } }