Last active
July 1, 2020 11:20
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} ); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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