A function for temporarily changing the WordPress post context

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:

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:

The function has helped me a number of times now and hopefully, it helps you too.

One last thing…

If you liked this article, I'd be incredibly grateful if you tweeted about it.

Also, I don't send emails often but when I do, I try to fill them full of useful goodies. If you like code snippets & dev tips, join my mailing list. There's no catch but I'll probably want to tell you about any new plugins & tools I build.