When to use global $post and other global variables?

I am trying to understand when and why I should use the global $post variable.
I have tried to do the following on a post page, outside the loop, and as expected it works.

    <?php 
        global $post;
        echo $post->ID;
    ?>

If I do the same on an archive page (just wanted to see what happens), for some reason it also works, retrieving the ID of the previous post, even if I deleted the code above from the previous post page.
Is this like some kind of caching? How does this work exactly?

I understand global $post can be useful if I’m working on a fuction in functions.php. Is this the only use case?

Many thanks

2 s
2

This is perhaps too broad a question to answer well. The $post global could be used in all sorts of ways. Whether or not it should be used depends on each circumstance.

However, as I understand it, the main intended purpose of the $post global is its use in theme template files.

When you use the_title() or the_content() or the_author() or any of the very many template functions, WordPress goes looking for this information in the $post global. As a general rule, when working in the template files, you will always want to use these template functions, like get_the_ID(), instead of accessing $post->ID directly.

So if you want to understand the $post global better, you should read up on how The Loop works in WordPress, particularly within the template files. When a Loop runs the_post(), it is setting up the global with the current item.

In template files, you’ll usually be iterating over a Loop for a query that is run automatically. When you access a single Page, for instance, WordPress knows to run a query for that page and load the page.php template.

If you want to retrieve extra posts outside of the main Loop, for instance in your functions.php, you would run your own WP_Query, initiate the Loop and then use the template functions. Only access the $post global directly if you’re unable to access the information you want through an existing function.

When you’re done looping over your own WP_Query, you’ll find that the $post global is now stuck on your custom query. So, for instance, on our single page template, after our custom loop, we may no longer have the current page set up in $post. You can restore the $post global to its former state with wp_reset_query. This is absolutely critical or else you can break other plugins or themes which expect the original $post global.

Leave a Comment