Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A function for temporarily overriding the WordPress post context. For more info see
* This is a rather simple and contrived example but it illustrates how this
* function can be used to temporarily change the post context.
$alt_post_content = override_post_context( 1234, function ( $post ) {
// Do whatever you need here. The $post variable, in this scope, is the
// $post object we are currently working with.
return ob_get_clean();
} );
* Easy overriding of current post object for using template tags dynamically.
* This is particularly useful if we need to use a template function that produces
* side effects but doesn't have a complete 'get_xxx' equivalent; e.g; the_content();
* @param int|WP_Post $alternative_post The post ID or object for the new context.
* @param Closure $callback A callback function that handles the calls to the
* required template tags and returns output.
* @return mixed
function override_post_context( $alternative_post, $callback ) {
global $post;
$post = get_post( $alternative_post );
setup_postdata( $post );
$return = call_user_func( $callback, $alternative_post );
return $return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.