Skip to content

Understanding PHP Globals and Variable Scope in WordPress

One of the most maligned features of WordPress is the use of “PHP global variables.” Whether you love them or hate them, thoughm global variables probably aren’t leaving WordPress soon.

So today we’ll cover all there is to know about WordPress’s PHP globals: how to think about them; how to make variables global in PHP; how to access WordPress’s global variables; and a little about the theory and debate about global state in software applications.

What Variable Scope Means in PHP

What this means is that any given unit of PHP will either have access to variables in the global scope, or only have access to the variables declared inside the currently executing function.

Scope is a popular brand of mouthwash in the United States. But it’s also, and more importantly, about what’s relevant and visible to who and where. People use the phrase “out of scope” when talking about activities or ideas that aren’t currently relevant to what they’re working on, and that’s got a lot to do with variable scope.

Programming languages like PHP are written such that variables are accessible only within in a certain context, or scope. This is done it various ways, and based on various rules in different languages. But the purpose of variable scopes is to prevent the problem that one part of a program may set $i to 5, and while it’s waiting to use that value, and another part sets it to 981235792 or “cucumber.” If they’re both using the same $i, one of those parts of the program is highly likely to malfunction.

Variables are given scope to prevent programs (and programmers’ heads) from exploding. The specific rules that control what variables are accessible in which places vary from programming language to programming language. What’s relevant to someone interested in WordPress and PHP is the specific way it works in that context.

PHP as a language uses function scoping. What this means is that any given unit of PHP will either have access to variables in the global scope, or only have access to the variables declared inside the currently executing function. And variables declared in a function are not going to be available globally unless they explicitly declare that they are. I could keep speaking abstractly, but I think it’s best if we get concrete with the PHP: we’ll declare global variables inside functions, and access global scope as well.

PHP Global Variable Example: Playing with Scope in PHP

In this section I just want to run you through what all this global variable scope stuff looks like in some basic PHP. Declaring a global variable, accessing a global variable, and more can be explained with this non-WordPress sample PHP code:

$global = "I am a global variable because I wasn't defined inside a function.";

function my_global_function() { 
     global $global; 
     echo $global;

function my_nonglobal_function($global) {
     echo $global;


function make_something_else_global() {
    global $second_global;
    $second_global = "I'm global becuase the word global was used inside a function.";
echo $second_global;

As we said in the last section, there are really only two relevant scopes in PHP for variables you create: global and function. (There is a third type of scope, but if you want to know more about superglobals like $_GET, $_POST, and $_REQUEST, but they’re too big of a topic to tackle here.)

Declaring: In PHP, Make a Variable Global

If you desire in PHP to declare a global variable, you can just do it outside of a function. That’s because any PHP variable that is not inside of a function (and thus isn’t function-scoped) is global. The value of the variable $global will simply work anyway after the line of code that declare it. And because we’re declaring $global outside of a function, it will automatically have global state.

But in a lot PHP for WordPress, you’ll be inside of a function. This is often because you’re working with a WordPress hook. To make a variable available everywhere (globally) from inside a function means that you must first declare that variable as global. Then you can assign that variable to anything you like. That’s what we’re doing inside of the make_something_else_global function in the code section above.

That’s how to set global variable in PHP: first make sure you’ll have a variable be global, either by position (outside of any function) or by using the global keyword. Then you just set it, or set it again. Even 100 times. PHP doesn’t care.

PHP Access Global Variable, “import” with global keyword

Inside of a PHP function, a global variables (declared elsewhere) can be accessed in two ways. First (and most common), is accessing it using the global keyword. This is what our first called function, my_global_function, does. By asserting that it wants the global variable $global, the echo — which is just PHP vocabulary for “throw onto the screen” — can output the string that we declared in the first line of the example. If we’d skipped the global line, we’d — depending on settings — either see a PHP error, or nothing on the screen at all. Neither is what we wanted.

This code shows another way that we can use the predeclared variable $global in the my_nonglobal_function. To do that, we can pass $global it into the function as a parameter. This allows us to be a little more certain about what variable we’re truly getting in the function, because it’s a hand-off. and it allows us to to skip straight to the echo $global without a stop off to “import” the variable. This is a way to avoid using to many PHP globals.

As you can see, these two functions that both accomplish the same thing. You’ll see both methods occur in various places in various PHP projects. Use of global has fallen out of favor in the PHP community because of the risk that before our function got around to access $global it could easily have been changed to anything and we’d be left having made a wrong assumption about it and quite possibly causing errors. The method of passing the relevant variables into the function when it is called is preferred in projects that don’t worry about backwards-compatibility as much as WordPress.

A PHP Global Array: Just like a Variable

One last note: you can assign almost anything to a (global) variable in PHP. Whether a string, object, or array, all you need to do to make a global array in PHP is to follow the step we outline above. Primarily: declare global $array that’s really all there is to make a PHP global array.

And while you might think, “I’m doing global better” because you only have “one” global array, I will caution you that from a precaution principle perspective, anything that varies independently should be consider a free global variable. Each element of that array is a global variable. Even if you’ve shoved them all in an array labelled, say, $global_array_of_variables.

WordPress Global Post ($post): Variable Scope in WordPress

As I said at the top, WordPress relies heavily on PHP global variables. (Here’s the list of all its globals.) As such, it is exceptionally common that you’ll see a function start with a line like:

global $post;

Hopefully by now you’ve got a pretty good idea of what this is doing: importing in the entire global $post variable — which template tag functions like the_title() (or ones you make yourself) rely on — to local scope so it can act on it. This is so common you’ll see people forgot the need to declare the global or add the line at the top of their function when it’s not really necessarily. (It’s usually unnecessary because the programmer never accesses anything on $post directly after they “import” it from the global scope.)

Another prime example, other than inside the loop with template tags like the_ID() and the_content() of where global scope is used within WordPress is the mythical Loop itself. If you’ve written a custom WP_Query you may have suspected it, but the way you can use object-less methods like have_posts() and the the_post() inside of your template hierarchy files is that under the hood you’re calling those same methods on a global instance of WP_Query that WordPress has set up for you. (I like to tell beginners to just think of this as a “magic bag of posts,” but under the hood experts understand that it’s just a WP_Query object.)

Should You Use Global Variables in PHP?

There are huge decades-long discussions in software development circles about why heavy reliance on globally scoped variables is a bad design decision. That debate is beyond the scope of what I want to cover here. (If that topic is interesting to you, the C2 Wiki article on it is a good starting point for understanding the arguments.) Suffice it to say that they’re bad because they can cause “spooky action at a distance.” Or, in other words, because global variables are “global,” someone else’s change to a global variable can break your code. And they were only able to do that because it’s a “global.”

The primary point in favor of global variables? They’re a relatively easy and robust way to share information in all the parts of a web application. As we’ll see, just drop the global keyword into your PHP and you’re off to the races.

What We’ve Learned about PHP Global Variables

Where you can avoid it, it’s generally considered a better idea to not add things to the PHP global scope. Given a choice between passing in a variable to the new function using it as a parameter, or adding your variable to the global scope, its best practice to do the former. But because WordPress is so conservative, global variables aren’t likely to leave us anytime soon. For that reason, you’ve earned a valuable power by understanding them. Happy hacking!

Yay! 🎉 You made it to the end of the article!
David Hayes

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
WP Video Tutorial
July 15, 2019 9:12 am

Excellent writing. Well explained the topic which helps the user or developer to understand. Thanks for the info.

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

Would love your thoughts, please comment.x

Most Searched Articles

Best JavaScript Libraries and Frameworks: Try These 14 in 2024

In this post, we look at the best JavaScript libraries and frameworks to try out this year. Why? Well, with JavaScript being available in every web browser, this makes it the most accessible programming language of ...

20 Best Free WordPress Themes for 2024 (Responsive, Mobile-Ready, Beautiful)

If you're looking for only the best free WordPress themes in the market for this year, then you're in the right place. We have more than enough such themes for you right ...

12 Best WordPress Hosting Providers of 2024 Compared and Tested

Looking for the best WordPress hosting that you can actually afford? We did the testing for you. Here are 10+ best hosts on the market ...

Handpicked Articles

How to Make a WordPress Website: Ultimate Guide for All Users – Beginners, Intermediate, Advanced

Many people wonder how to make a WordPress website. They’ve heard about WordPress, its incredible popularity, excellent features and designs, and now they want to join the pack and build a WordPress website of their own. So, where does one get ...

How to Start an Ecommerce Business: Ultimate Guide for 2024

Is this going to be the year you learn how to start an eCommerce business from scratch? You’re certainly in the right place! This guide will give you a roadmap to getting from 0 to a fully functional eCommerce business. ...