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()
.
- Global. WP_Query.
$wp_query
Global WP_Query instance.
No Hooks.
Return
Nothing (null).
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 ?>
Code of wp reset postdata:
wp-includes/query.php
VER 5.0.3
Related Functions
From tag: reset
More from category: Queries
- get_page_by_title()
- get_post()
- get_posts()
- have_posts()
- in_the_loop()
- is_404()
- is_archive()
- is_attachment()
- is_author()
- is_category()
- is_date()
- is_day()