<?php

$WP_POST_STACK = array();

function switch_to_post($post_id) {
	global $WP_POST_STACK, $post;

	// Initialize the stack with very first $post->ID
	if ( !count( $WP_POST_STACK ) ) {
		$WP_POST_STACK[] = $post->ID;
	}

	// Stick our new post_id onto the end
	$WP_POST_STACK[] = $post_id;
	$post = get_post( $post_id );
	setup_postdata( $post );
	do_action( 'switch_to_post', $post_id );

	return true;
}

function restore_post() {
	global $WP_POST_STACK, $post;

	// If we don't have anything to knock off, just return
	if ( count( $WP_POST_STACK ) ) {
		// Remove the current post_id off the stack
		$removed_post_id = array_pop( $WP_POST_STACK );
	
		// Get last value of the array but leave it on the array
		if ( $post_id = end( $WP_POST_STACK ) ) {
			$post = get_post( $post_id );
			setup_postdata( $post );
			do_action( 'restore_post', $post_id, $removed_post_id );
			return true;
		}
	}
	return false;
}