wp_reset_postdata() WordPress Function

The wp_reset_postdata() function allows you to reset the global $post variable to the original post in the main query. This is useful if you have used $post in a custom loop outside of the main query.

wp_reset_postdata() #

After looping through a separate query, this function restores the $post global to the current post in the main query.


More Information

Use this function to restore the context of the template tags from a secondary query loop back to the main query loop.

Differences between the main query loop and secondary query loops are:

  • the main query loop is based on the URL request and is initialised before theme templates are processed
  • secondary query loops are queries (using new WP_Query) in theme template or plugin files

A secondary query loop using $sec_query = new WP_Query() and $sec_query->the_post() affects the global $post variable. The global $post variable is used by template tags by default. wp_reset_postdata() restores the global $post variable to the current post in the main query (contained in the global $wp_query variable as opposed to the $sec_query variable), so that the template tags refer to the main query loop by default again.

Example


<?php 
$args = array( 'posts_per_page' => 3 );

// the query
$sec_query = new WP_Query( $args );
?>

<?php if ( $sec_query->have_posts() ) : ?>

<!-- start of the loop. the_post() sets the global $post variable -->
<?php while ( $sec_query->have_posts() ) : $sec_query->the_post(); ?>

    <!-- template tags will return values from the post in the $sec_query object
    <?php the_title(); ?>
    <?php the_excerpt(); ?>

<?php endwhile; ?><!-- end of the loop -->

<?php else: ?>

<?php _e( 'Sorry, no posts matched your criteria.' ); ?>

<?php endif; ?>

<!-- reset global post variable. After this point, we are back to the Main Query object -->
<?php wp_reset_postdata(); ?>


Top ↑

Source

File: wp-includes/query.php

function wp_reset_postdata() {
	global $wp_query;

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


Top ↑

Changelog

Changelog
VersionDescription
3.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.