Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/2352830fd31b50a87a2748efdca6b0e4 to your computer and use it in GitHub Desktop.
Save mishterk/2352830fd31b50a87a2748efdca6b0e4 to your computer and use it in GitHub Desktop.
A function for temporarily overriding the WordPress post context. For more info see https://philkurth.com.au/tips/a-function-for-temporarily-changing-the-wordpress-post-context/
<?php
/*
* 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 ) {
ob_start();
// Do whatever you need here. The $post variable, in this scope, is the
// $post object we are currently working with.
get_template_part('some/template');
return ob_get_clean();
} );
<?php
/**
* 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 );
wp_reset_postdata();
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment