A function for temporarily changing the WordPress post context
Last updated • October 4th, 2019
If you’ve ever found yourself in a situation where you need to render something from some other post whilst in the context of another, you may have ended up just overriding the global $post variable. It works fine but can be problematic where you mess it up or just forget to clean up after yourself.
Being as picky as I am, I usually find myself cringing at the resulting template code. It always ends up feeling like a bit of a mess and it’s always a little bit of a speed hump to have to think about how to tackle the situation whenever I’m in it.
So, to help things along, I threw together a function that allows me to specify an alternative post – either by ID or with the WP_Post object itself – and pass it an anonymous function where I run whatever code I need.
Here’s a look at the function:
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
To use it, you just need to pass the post you want to work on along with your callback which needs to return something. This can be markup or data for you to working with.
Here’s an example of how to use it:
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