Using Global Variables in WordPress

Using Global Variables in WordPress

A global variable, as it name suggests, is simply a type of variable that is available for use within any fraction of your codes. PHP’s global variables and all their glory can be used within WordPress to help you eliminate code duplication, and in some situations save you some database queries.

Even though many developers think that using global variable is simply a bad practice, if you use it the right way there would be next to none problem you will have to face. Within the scope of this article, I will try my best to describe how you can make good use of global variables while working with WordPress.

Global Variables in general

(This is the basic section so you can just skip it if you like.)

Define a global variable

You define a global variable the same way you would define any variable: var $my_global_var = 'global value'; or simply $my_global_var = 'global value';. There are three things you have to keep in mind, however:

You have to choose a unique name for that global variable, otherwise you will end up replacing global variables defined by other plugins, themes or WordPress’s core files themselves.

You have to declare them as global or use $_GLOBALS within a function

Choosing a unique name

This task looks easy at first, but the more variables you create, the harder it becomes and you might eventually define a variable that has a weird and uninformative name. The point is you not only have to choose a unique name, but you also have to make it good.

While there are plenty of naming conventions out there for you to choose, the most important thing you need to consider is consistency (use only one naming convention and stick with it).

Basically, there are two good naming practice you can use, either:

$myVariable = 'value';
// first word is always in lower case
// if you have more than one word, the second and beyond are capitalized

Global Variables within a function

If you want to define or use a global variable inside a function, you will have to declare it with the keyword global or use $_GLOBALS['your_global_var_name'], otherwise it will be registered as a local variable which is only accessible inside that function.

You get the idea, the highlighted line tells the function to use the variable in the global scope instead of its local scope. $bar is not defined inside test() and therefore is NULL or empty.

Working with the variable

Now that you have defined your desired global variable, the next step is decide how you set and get the value from it.

The simplest method is to use $my_global_var = 'new global value'; when you want to change its value, or $other_var = $my_global_var; when you want to get its value. Also remember to declare global $my_global_var; if you are inside a function.

This method works most of the time, but there is a more elegant way to do that actually: using global functions.

Global functions also need to be unique and follow some naming conventions. However, to keep things simple, you can just use:

// the function to get the global variable
function youruniquekey_get_var()
{
global $my_global_var;
return $my_global_var;
}
// now get it in any place you want, even inside another function
function do_something_cool()
{
$other_var = youruniquekey_get_var();
echo $other_var; // show the global variable
}

As you can see, declaring global $my_global_var; is not needed anymore when you want to get the value of that variable. Make sure that you replace youruniquekey with something meaningful, for example ‘betterwp_postmeta’.

If you are changing the value of $my_global_var instead of getting, simply use the same code with some minor adjustments:

Make use of global variables in WordPress

Ah.. here comes the fun part :). In case you don’t know, WordPress itself uses many global variables, some of which are in constant use when you write plugins or themes. You can, of course, define your own global variables and use them as you wish (keep in minds those tips above, though.)

Example uses of built-in global variables

Three of the most important global variables defined by WordPress are: $wp, $wp_query1, and $wp_rewrite2.

As their names suggest, $wp contains important values used when WordPress initializes, while $wp_query contains values related to the current queried page, and $wp_rewrite contains all the rewrite rules currently in used (plus other related data).

Now please pay attention to this property: public_query_vars. It is an array that holds publicly queriable variables that you can use to get data from the database by appending them to your URL. For example, you will be able to view posts from the Uncategorized category by simply appending ?category_name=Uncategorized to your URL.

The default public query variables might not be used at all if you enable nice permalinks (most people do) so why is knowing this useful? Because, by using filters, you can add your own queriable variables thus opening up a whole load of possibilities.

Let’s say you want to allow your visitor to sort your posts from a particular category. The normal approach would be creating two pages with two different query_posts()3 with different ‘order’ argument.

In fact, you will only need one query_posts() if you use a custom queriable variable. To add such variable, you must use a filter, like so:

Please note that if you ignore the query_vars filter and simply append the custom variable to the URL, WordPress will not accept it and $_GET['sort'] will be undefined.

You can even make this more elegant by using nice links, e.g. yourdomain/category/test/asc/. It is slightly more complicated involving the use of $wp_rewrite, which I am going to tell you about right now.

The WP Rewrite object: $wp_rewrite‘s structure is a little more complex:

To achieve our goal (sorting with nice permalinks), the only thing you need to care about is the rules property. It is yet another array and you and extend it with your own rewrite rules, in this case you will have to tell WordPress to rewrite yourdomain/category/test/asc/ to something like this: yourdomain/?category_name=test&sort=asc.

To do this, simply repeat what we have done above plus inserting this snippet into your theme or plugin:

Most of the time your new rewrite rules will not be used right away as you will have to flush the old rules first. To flush old rewrite rules, go to Settings → Permalinks and then optionally click on Save Changes.

That’s it! Now you can browse to yourdomain/category/test/asc/ or yourdomain/category/test/desc/ and you will be greeted with sorted posts as expected.

Custom global variables

By now you should have a hold of global variables and how to make use of some built-in ones, I think it’s time to create your very own!

The idea is not how you would define your global variables but what should be made global. If you are developing a new website, you will need, for example, footer links, menus, permalinks all over the places.

While you can, or course, fetch them when you need, you can do it the more efficient way. In other words, all variables that you refer to more than once, you should fetch them in one place, make them global, and then get the global values when you need. WordPress itself does cache queried data fetched from the database, but why relying on something complex and uneasy to control?

Following what I have written in the general section, I will go ahead and create a new global variable called $bwp_cache. You can define this variable either as an Array4 or as an Std Object5, but it is recommended to define it as an array for easier manipulation.

Please note that if you want this variable to be global, you will have to define it in “global” files, such as wp-config.php, functions.php or a plugin’s files. If you define it in some local template files, such as header.php, be sure to have this global $bwp_cache;.

In this example I will get some footer links and try to build permalinks to my plugin page, my tip page and my archive page in my menu. The full codes are as below:

I can now access those data anywhere I want using bwp_get_var or bwp_the_page_link. For example, in my menu.php I would like to display links to the three pages mentioned above without the need of get_permalink()7:

No. Global variables are hardly ever a good idea. This article justified their use. It is well known bad coding practices. Global variables are WordPress’ achilles heel. You should be encouraging people how to avoid globals in WordPress wherever possible by using member functions instead like get_query_var()

[...] eh? You can still give up now if you want . The snippet above makes use of two global variables11 with $bwp_shortcode_matches used to store all shortcode contents and $bwp_shortcode_hash used to [...]

[...] more you should know all the functions that allow you to check what page you’re on as well as how to use some global variables in WordPress. After WordPress calls wp() most functions and global variables you need are already [...]

[...] the former method is what you prefer, check out this article of mine about WordPress Global Variables to have a better understanding of what you can do to re-use as many variables as possible, using [...]