Back to Top

Using Global Variables in WordPress

Previous Post:

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


$my_variable = 'value';
// all words should be in lower case

Check out other articles in Further Reading section for more details.

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.

An example taken from for quick understanding:

$foo = 'global variable';
$bar = 'global variable, too';

function test() {
    global $foo;
    echo '$foo is a ' . $foo . "\n";
   // or echo '$foo is a ' . $_GLOBALS['foo'] . "\n";
    echo '$bar is a ' . $bar . "\n";


This will output:

 * output
 * $foo is a global variable
 * $bar is a

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:

// the function to set the global variable
function youruniquekey_set_var($new_value)
	global $my_global_var;
	$my_global_var = $new_value;
youruniquekey_set_var('new global value');

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).

The WP Object ($wp) is something similar to this:

WP Object
    [public_query_vars] => Array
            [0] => m
            [1] => p
            [2] => posts
            [3] => w
            [4] => cat
            [5] => withcomments
            [6] => withoutcomments
            [7] => s
            [8] => search
            [9] => exact
            [10] => sentence
            [11] => debug
            [12] => calendar
            [13] => page
            [14] => paged
            [15] => more
            [16] => tb
            [17] => pb
            [18] => author
            [19] => order
            [20] => orderby
            [21] => year
            [22] => monthnum
            [23] => day
            [24] => hour
            [25] => minute
            [26] => second
            [27] => name
            [28] => category_name
            [29] => tag
            [30] => feed
            [31] => author_name
            [32] => static
            [33] => pagename
            [34] => page_id
            [35] => error
            [36] => comments_popup
            [37] => attachment
            [38] => attachment_id
            [39] => subpost
            [40] => subpost_id
            [41] => preview
            [42] => robots
            [43] => taxonomy
            [44] => term
            [45] => cpage
            [46] => post_type

    [private_query_vars] => Array
            [0] => offset
            [1] => posts_per_page
            [2] => posts_per_archive_page
            [3] => showposts
            [4] => nopaging
            [5] => post_type
            [6] => post_status
            [7] => category__in
            [8] => category__not_in
            [9] => category__and
            [10] => tag__in
            [11] => tag__not_in
            [12] => tag__and
            [13] => tag_slug__in
            [14] => tag_slug__and
            [15] => tag_id
            [16] => post_mime_type
            [17] => perm
            [18] => comments_per_page

    [extra_query_vars] => Array

    [query_vars] =>
    [query_string] =>
    [request] =>
    [matched_rule] =>
    [matched_query] =>
    [did_permalink] =>

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:

add_filter('query_vars', 'insert_custom_qv');

function insert_custom_qv($variables)
	array_push($variables, 'sort');
	return $variables;

You should put this snippet inside your theme’s functions.php or inside a plugin. This simply appends the public_query_var array with our custom variable: sort.

Now in your category.php or any theme file used to display posts from a category, place these codes (this also makes use of $wp_query):

$sort = (!empty($_GET['sort']) && 'asc' == $_GET['sort']) ? 'asc' : 'desc';

		array('order' => $sort),

For your visitors to sort the posts, you can provide two links appended with the sort variable above, e.g.

<a href="?sort=asc">Show older posts first</a> | <a href="?sort=desc">Show newer posts first</a>

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:

WP_Rewrite Object
    [permalink_structure] =>
    [use_trailing_slashes] =>
    [category_base] =>
    [tag_base] =>
    [tag_structure] =>
    [author_base] => author
    [search_base] => search
    [comments_base] => comments
    [feed_base] => feed
    [comments_feed_structure] =>
    [front] =>
    [root] =>
    [index] =>
    [matches] =>
    [rules] => Array()
    [extra_rules] => Array()
    [extra_rules_top] => Array()
    [non_wp_rules] => Array()
    [extra_permastructs] => Array()
    [endpoints] => Array()
    [use_verbose_rules] =>
    [use_verbose_page_rules] =>
    [rewritecode] => Array()
    [rewritereplace] => Array()
    [queryreplace] => Array()
    [feeds] => Array()

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:

add_filter('rewrite_rules_array', 'insert_custom_rules');

function insert_custom_rules($rules)
	$newrules = array();
	$newrules['category/(.+?)/(asc|desc)/?$'] = 'index.php?category_name=$matches[1]&sort=$matches[2]';
	return $newrules + $rules;

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 SettingsPermalinks 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:

$bwp_cache = array();
// Footer links
$footer_links = get_bookmarks(array('category_name' => 'Footer', 'orderby' => 'id', 'limit' => -1)); // _6
// Permalinks
$page_perma_structure = '';
// Add values
$bwp_cache['links_footer'] = $footer_links; // you can have links_header, links_sidebar, etc.
$bwp_cache['perma_struct_page'] = $page_perma_structure; // you can have perma_struct_single, perma_struct_custom, etc.

function bwp_get_var($key)
	global $bwp_cache;
	return (isset($bwp_cache[$key])) ? $bwp_cache[$key] : '';

function bwp_the_page_link($pagename)
	echo str_replace('%pagename%', $pagename, bwp_get_var('perma_struct_page'));

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:

<ul class="menu">
	<li><a href="<?php bwp_the_page_link('wordpress-plugins'); ?>">WordPress Plugins</a></li>
	<li><a href="<?php bwp_the_page_link('wordpress-tips'); ?>">WordPress Tips</a></li>
	<li><a href="<?php bwp_the_page_link('archives'); ?>">Archives</a></li>

In footer.php, or any other files, to display a list of footer links, I use this:

$footer_links = bwp_get_var('links_footer');
if (isset($footer_links) && sizeof($footer_links) > 0)
	foreach ($footer_links as $key => $link)
		// output links

… yes, simple as that!

The Bottom Line

There are many ways to build things in WordPress, and using global variables is simply one of them. Not everyone finds it suitable, but the benefit is rather clear.

I think this article is a good start for any of you who are trying to use global variables in your upcoming WordPress project. I hope you’ll find this article useful, and stay tuned for any follow-up!

Further Reading

  1. Zend Framework – Naming Conventions
  2. PHP Standards
Remember to declare


  1. []
  2. ... WP_Rewrite []
  3. ... uery_posts []
  4. []
  5. []
  6. ... _bookmarks []
  7. ... _permalink []

Take Social Sharing to
the Next Level with Monarch!

Take Social Sharing to the Next Level with Monarch!
Print Article Trackback Trackback to this Article   Subscribe to Comments RSS Subscribe to Comments RSS

13 Opinions for Using Global Variables in WordPress (5 Trackbacks)

  1. User's Gravatar
    jim April 4, 2011 at 7:04 am – Permalink

    Thanks 🙂

  2. User's Gravatar
    dung March 8, 2012 at 11:33 pm – Permalink

    very useful and well written article!

  3. User's Gravatar
    bajji7179 April 18, 2012 at 11:41 pm – Permalink

    salut ca va ? je suis un débutant en wordpress
    j’ espères que vous pouvez m’aider de résoudre mon problème ……
    je veux déclarer une variable dans header de Template(theme) et la changer chaque fois dans plusieurs endroit

    • User's Gravatar
      OddOneOut April 19, 2012 at 9:32 pm – Permalink

      If you want to make a variable such as $my_variable global, you must declare it as global in your header template file (header.php). This should work:

      // In header.php
      global $my_variable;
      // In any theme file
      echo $my_variable;

      That’s it.

      • User's Gravatar
        Dasha March 6, 2014 at 9:12 pm – Permalink

        Great article, thank you!
        Just to double check.. before we declare a variable with keyword ‘global’, do we need to check first if it already exists, for example:

        // In header.php
        if ( ! isset( $my_variable ) ) {
        	global $my_variable;

        Let me know what you think.

        • User's Gravatar
          Khang Minh March 8, 2014 at 1:07 am – Permalink

          That’s not required. What’s more important is you need to make sure that $my_variable has the data you’re expecting.

  4. User's Gravatar
    Broeiend July 6, 2013 at 10:28 pm – Permalink

    This has proven to be a valuable article for me. Thank you very much!

  5. User's Gravatar
    Mike October 23, 2015 at 9:26 am – Permalink

    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()

  1. Protect Shortcodes from wpautop and the likes «

    [...] 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 [...]

  2. Selective Plugin Loading «

    [...] 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 [...]

  3. Create Fake Pages in WordPress - Better WordPress

    [...] tag for your HTML document, but generally, you can use the optional $showing_title global variables1 to construct <title>, like so: [...]

  4. Speed Up WordPress: A Developer's POV - Better WordPress

    [...] 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 [...]

  5. My Lessons

    [...] [...]

Speak Up Your Mind!

An asterisk (*) indicates a required field and must be filled.

  • Web page and e-mail addresses turn into links automatically.
  • Wrap codes in: <code lang=""></code> or <pre lang="" extra="">
  • Lines and paragraphs break automatically.

Next Post: