Accessing WordPress Application Objects with PHP Global Variables

PHP Global Variables are a wonderful thing, allowing us to access data objects outside of our immediate function. Here’s an example in a WordPress Plugin I’m currently writing.

In the plugin we’re using a WordPress Filter to append a message to the post content based on post metadata we’ll be providing. Some posts will have that metadata, some won’t.

We’ll start with the add_filter() method where we are restricted to passing the post content in “the_content” property.  There is no “the_post” option.  Well, there is, but it passes an array of all posts, not the current post.

Here’s the filter_show_redirector() function where we’re passing the post’s content. As I mentioned, we need to retrieve the post metadata and to do so we use PHP global variables to access the current WordPress post object.

That’s the example of using a global PHP variable to access a WordPress application object, but before signing off let’s look at this a bit more in IntelliJ IDEA Debug Mode.

As we step through the code we can see the wealth of objects available to us in WordPress.  At bottom we see the post object properties, where we used the post object in our add_filter() function to retrieve the post’s meta data with get_post_meta($post->ID,…).

Here is another final view of other variables available to us, where most WordPress-specific application objects we’ll be interested in are in the $GLOBALS array.