switch_to_post() stack implementation (similar to switch_to_blog())
|Reported by:||alexkingorg||Owned by:|
One of the challenges themes and plugins have is the balance between utilizing the core APIs that rely on global variables, while leaving things in a "clean" state for the next worker in the chain.
For example, I might have a shortcode that pulls content from another post, outputs a title or some other data, then needs to restore the previous post environment. The attached patch provides APIs for doing just this - using the same stack approach that switch_to_blog() takes in a multi-site instance.
To set up a post context, call: switch_to_post($post_id);
This can be called multiple times, diving deeper into the stack. Then each process is responsible for restoring the $post context by calling: restore_post();
This goes back to the stack, bumps out the current post and restores the previous post's context.
There is some test code for demonstration here: