WP_REST_Revisions_Controller::restore_post_data( WP_Post|null $previous_post )

In this article

This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only by core. It is listed here for completeness.

Restores the global post to its previous value after preparing a revision.

Description

Preparing a revision overwrites the global post and post data via setup_postdata() . This restores the global post that was in place beforehand so the change does not leak into the rest of the request.

Only the global post is guaranteed to be restored. When there was no previous global post and the main query has no post either, which is the usual state during a REST request, wp_reset_postdata() has nothing to restore from, so the remaining globals set by setup_postdata() (such as $id, $authordata and $pages) are left describing the revision. Clearing those would mean unsetting each one by hand, which is beyond what is needed to keep the global post from leaking.

Parameters

$previous_postWP_Post|nullrequired
The global post to restore, or null if there was none.

Source

private function restore_post_data( ?WP_Post $previous_post ): void {
	if ( $previous_post ) {
		$GLOBALS['post'] = $previous_post;
		setup_postdata( $previous_post );
		return;
	}

	/*
	 * There was no global post to restore, so clear the revision's post data.
	 * This runs before clearing the global post because wp_reset_postdata()
	 * repopulates it from the main query whenever that query has a post. Note
	 * that it is a no-op when the main query has no post, in which case only
	 * the global post below is cleared.
	 */
	wp_reset_postdata();

	/*
	 * Assigned rather than unset so that any `global $post` binding made before
	 * this request keeps pointing at the global. Unsetting removes the entry from
	 * the symbol table, which detaches those bindings, and a later write through
	 * one of them would no longer be visible to get_post().
	 */
	$GLOBALS['post'] = null;
}

Changelog

VersionDescription
7.1.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.