Why declare $post globally?

In the tutorial (Example 1), he has to declare the global $post so that he can access the post_parent from it. In a function like that, the $post is not a global variable unless he makes it so.

In the codex (Example 2), it is declared global because the sample code is just a sample, explicitly trying to tell you that the $post variable is a global one.

Now, while Theme Templates are included in such a way that they are running within the global variable space (they are included from the main execution thread, not from inside a function), other code may not be. So, in the main body of a template, you would not need to specify global $post, but in a function you would.

Understand also that WordPress is geared towards programmers of all skill levels. You should not need to be master programmer to be able to get things done, when your goal is simply to make a change to your theme or website or something along those lines. WordPress evolved from a basic procedural piece of code to being more object oriented and API based over time. So there are relics like these within the codebase. If you were designing a new system from the ground up, you probably would avoid using global variables entirely, for various reasons. WordPress contains a lot of them for backward compatibility and such, and “new” programmers who might not understand variable scoping might be confused when they copy a small piece of code into a place where it won’t work because of that scoping. Thus, declaring things as global explicitly avoids problems and also makes the code clearer by stating that the variable in question is in the global scope.

Also, and I have to say this a lot, code examples in documentation and tutorials are meant to be read and understood, not copied and pasted. But people do copy and paste them, regardless. It is better to not copy code, but to learn what it tells you and then write your own version from scratch, which does exactly what you are trying to do.

Leave a Comment