WordPress at Your Fingertips

Global Variables in WordPress

We often use functions to retrieve some data on a page and are unaware that this data can be taken from global variables. For example, the name of the author on the author page. And sometimes we just don't know how to get the data we need, where they are. This article will tell about how to get all the important data of the current page from the variables of PHP, which are already defined in WordPress. Such data only remains to take.

I should note that if there is an equivalent option to get the data through a function, it's better to get it through a function. Because it can get rid of bugs in the future - when you update in future versions, the name of the global variable may change. And it is unlikely that the name of the function will change. Besides, changed functions are not deleted but get moved to the forbidden section, but still continue to work. Here is an example:

// The current user can be accessed via the global variable
global $current_user;

// or through a function, which is preferable
$current_user = wp_get_current_user();

What are global variables?

These are PHP variables that are "visible" everywhere.

To access a global variable, you have to prefix it with the global keyword:

<?php
global $cat;
echo $cat;

Or you can use the super-global array $GLOBALS:

<?php echo $GLOBALS['cat']; ?>

Global variables are ordinary variables that are defined in the global scope (main part) of PHP. To understand what a global scope is, imagine the very first php file, usually index.php - this is the global code area (global scope). If you define a variable in such a file, it will automatically become global. But if you create a function within such a file and define a variable inside of that function, it will be local -- the scope of such a variable does not go beyond the function. The same applies to classes and their methods (functions).

And what if another file is included in the "global" file? Suppose we include another file wp-load.php - require_once 'wp-load.php; to the main file index.php. The code of this connected file also becomes global, and the variables directly defined in this file automatically becomes global.

Let's look at an example. Suppose we insert the code below into the functions.php theme file, which in turn is included in the global scope, and any variables specified directly in it become global.

<?php
$var = 'Hello world!'; // this variable becomes global

// function
function my_func(){
	echo $var;
}
my_func(); // call: we will get a Notice level error,
		   // because there is no $var variable in the scope of the function

// function
function my_func2(){
	global $var; // define $var globally

	// now $var is a global variable

	echo $var; // hello world!

	// let's change the variable, it's a global variable
	$var = 'Bye-bye.';
}
my_func2(); // print: 'hello world!'

// print variable $var outside of functions
echo $var; //will print: 'Bye-bye.'
		   //because we changed global $var in function my_func2()

This code explains the essence of global variables, how they are visible and not visible within functions.

A global variable can be created from a local scope, for example from a function:

<?php
echo $var; // this will cause an error - the variable is not defined

function my_func2(){
	global $var; // create a global variable $var

	$var = 'hello world';
}
my_func2(); // call the function

echo $var; // print 'Hello world'

Note: The global keyword exposes a reference to the specified variable, rather than creating a new one. The following constructions are equivalent:

global $var;

// the same as

$var = & $GLOBALS['var'];

Important: Use global variables with caution!

There are a lot of global variables and they are easy to change. For example, if you write $id = 2; at the beginning of header.php theme files, the global variable $id which contained the ID of the current entry will change and cannot be used!

Similarly, the theme or plugins can change global variables. But still, there are some "defined" variables, that every developer should be aware of, and not use them as a global variable when creating a plugin or theme. This is exactly the list you will find in this article.

I do not recommend you to use variables not mentioned in this article in your code. You should find an alternative way to get the required data instead, e.g. using the appropriate function.

Global Variables in WordPress

During page generation, WordPress gets a bunch of data and important data is stored in global variables. For example:

  • The category ID on the category page is $cat.
  • Or all the posts received on a category page - $wp_query.
  • Or the post object on the post page - $post.

So, WordPress creates a bunch of global variables that you can use in your code. Let's look at the most important ones below.

Common variables

$wp_query(object)
Stores request for records of the current page. Global class instance WP_Query.
$wp_rewrite(object)
Stores everything about URL rewrite rules. Global class instance WP_Rewrite.
$wp(object)
Stores the current query of WordPress itself, where the query parameters obtained from the URL, etc. are specified. Global WP class instance.
$wp_scripts(WP_Scripts)
Stores all connected and put to output scripts. Global instance WP_Scripts.
$wp_styles(WP_Styles)
Stores all connected and rendered styles. Global instance WP_Styles.
$wpdb(object)
Stores the current connection to the database. Global class instance wpdb. Allows communication with the database.
$table_prefix(string)
Prefix a table in the database.
$wp_admin_bar(WP_Admin_Bar)
All data of the admin bar.
$wp_meta_boxes(array)
Object of all registered metaboxes. Contains their IDs, parameters (args), callback functions and headers of all record types, including arbitrary ones.
$wp_registered_sidebars(array)
All data about registered areas for the sidebar.
$wp_registered_widgets(array)
Data of all registered widgets.
$wp_registered_widget_controls(array)
____
$wp_registered_widget_updates(array)
____
$allowedposttags(array)
Allowed HTML tags when publishing an entry. See file for list wp-includes/kses.php.
$allowedtags(array)
Allowed HTML tags when posting comments. See the list in the file wp-includes/kses.php.
$wp_filter(array)
All WordPress hooks.
$wp_actions(array)
An array with event names in the index and the number of times the event was triggered in the value.
$wp_object_cache(WP_Object_Cache)
The entire object cache. It's stored this way when the object cache plugin isn't installed... Global class instance. WP_Object_Cache.
$shortcode_tags(array)
All registered shortcodes and their data.
$wp_embed(WP_Embed)

The class responsible for embedding objects. For example, when HTML code of youtube video link is created in the text of an article. The variable contains an instance of the class WP_Embed.

This class is based on the class WP_oEmbed - It contains the basic functionality of the embeds, and WP_Embed is a kind of wrapper. You can get the WP_oEmbed object through a function: _wp_oembed_get_object(). Separately, this object has no global variable.

$wp_oembed(WP_oEmbed)
There is no such global variable! You can get the WP_oEmbed object through a function: _wp_oembed_get_object().
$wp_taxonomies(array)
Data of all taxonomies.
$wp_post_types(array)
Data of all record types. Object array WP_Post_Type
$l10n(array)
An array of all translations. Contains MO class objects obtained from .mo files. See load_textdomain().
$l10n_unloaded(array)
An array of domains for which translations have been unloaded (cancelled). An array with elements: 'domain' => true. See unload_textdomain().
$wp_post_statuses(array)
An array of data about all the statuses of entries. publish, future, etc.
$current_user(WP_User)
The data object of the current user is an instance of WP_User. Some of the data is stored in separate global variables for quick access: $user_login, $user_ID, $user_email, $user_url, $user_identity (Usually login).
$wp_roles(WP_Roles)
All data of user roles on site.
$wpsmiliestrans(array)
An array of special strings that can be translated into emoticons. Translate text into smilies. :x into smiley, :| Into smiley, etc.
$super_admins(array)
An array of IDs of users who have extra super-administrator rights in MU build. This global variable is set by the site owner (e.g. in the wp-config.php file). If set, the variable overwrites (overwrites) the list of super-admins in the database.
$content_width(number)
Sets the width of the site content. Used in the file functions.php.
$wp_filesystem(object)

An instance of the selected object extending the class WP_Filesystem_Base, for working with files on the server. An instance can be one of the classes: WP_Filesystem_Direct, WP_Filesystem_FTPext, WP_Filesystem_ftpsockets, WP_Filesystem_SSH2.

Variable set by the function WP_Filesystem().

$wp_theme_directories
An array containing the paths to the folders where the themes are located. Usually there is only one path. The variable is created with the function register_theme_directory().

Localization (translation)

$wp_locale(WP_Locale)
Data of the current site locale (site language). Global instance класса WP_Locale.
$locale(string)
Site locale, for example ru_RU.
$weekday(array)
Array of all days of week translated to current locale. [ __('Sunday'), __('Monday'), ... ]
$weekday_initial(array)
Array of first letters of all days of week translated to current locale. [ __('Sunday') => __('S'), __('Monday') => __('M'), ... ]
$weekday_abbrev(array)
An array of short names of all days of week translated to current locale. [ __('Sunday') => __('Sun'), __('Monday') => __('Mon'), ... ]
$month(array)
An array of all months translated to the current locale. [ __('January'), __('February'), ... ]
$month_abbrev(array)
An array of abbreviated names of all months translated to the current locale. [ __('January') => __('Jan'), __('February') => __('Feb'), ... ]

Inside the WordPress loop

Inside the posts loop

You can use these global variables inside the WordPress loop. They change as you go through the items in the loop. They all contain information about the current entry (post) in the loop.

$posts(array)
All posts of the current cycle. The WP_Post object array. This variable doesn't change inside the loop but directly refers to it, so it's also in this list.
$post(WP_Post)
The object of the current post. On the record page it is the record itself. On the headings page it is the current entry in the loop.
$authordata(WP_User)
The object of the author of the current post. The object is described in WP_User.
$currentday(string)
The day when the current post was published.
$currentmonth(string)
The month when the current post was published.
$page(number)
The page of the current post, when the post is paginated Using the tag. <!--nextpage-->.
$pages(array)
The content pages of the current entry (post). Each page is paginated here using the tag <!--nextpage-->.
$multipage(true/false)
Determines whether the current post is paginated using the <!--nextpage-->. Contains true or false.
$numpages(number)
Number of pages if the entry is paginated with a tag <!--nextpage-->.
$more(true/false)
Whether there is a tag <!--more--> in the post content.

In the comments loop

$comment(WP_Comment)
The object of the current comment in the loop. See the description for an example of such an object get_comment()

All WP_Query variables

The main query WP_Query is saved in the global variable $wp_query. And all variables of this query are stored in separate global variables. Thus, we can get data from the global scope.

  • $author_name — Author's name (on the author's page)
  • $author — Author ID (on the author page)
  • $post_parent — The ID of the parent post. For attachments and tree entries.
  • $subpost
  • $subpost_id
  • $attachment
  • $attachment_id
  • $pagename — page label (on the page of the page)
  • $page_id — page ID (on the page of the page)
  • $hour — hour (on the date archive page)
  • $day — day (on the date archive page)
  • $monthnum — month number (on the date archive page)
  • $year — year (on the date archive page)
  • $w — day number of the week (on the date archive page)
  • $category_name — section name
  • $tag — subject name
  • $cat — rubric ID
  • $tag_id — title ID
  • $s — search request (on the search page).
  • $post_type — Record type (on record page)
  • $paged — Page number of pagination page.
  • $posts_per_page — Numbers of records per page.
  • $comments_per_page — Nb of comments per page.
  • $query_string — String (parameters) of current query.
  • $posts — All records of the current WP_Query
  • $post — Object of the current query. Current record ID: $post->ID.
  • $preview — True if previewing record.
  • $request — Last SQL query to get all records.
menu

In the Front Part (Front-end)

$template(string)
The path to the template file that is responsible for outputting the HTML code of the current page. For example: C:/sites/wptest.com/www/wp-content/themes/twentyfifteen/archive.php

In the Admin Panel

$current_screen(array)
The data of the current admin screen. See. get_current_screen()
$pagenow(string)

Determines what page we are on now - the current page of the admin panel. Stores the name of the php file that handles the current page. For example options-general.php. It takes the last element taken from $_SERVER['PHP_SELF'] and standardizes the value where needed.

The variable is set early, immediately after the event muplugins_loaded, but before the event plugins_loaded.

The variable is also set at the frontend, only there it almost always contains index.php or wp-login.php.

$post_type(string)
Record type in the admin. On the record or taxonomy page.
$menu(array)
Array of data with the admin menu items that were added via add_menu_page(). Contains an Array of data arrays for each menu.
$submenu(array)
Array of data with the admin sub-menu items that were added via add_submenu_page(). Contains an Array of data arrays of each sub-menu.
$admin_page_hooks(array)

The main menu items of the admin menu in the array. Where the array index is the menu ID, which is specified in the fourth parameter add_menu_page().

It is almost the same as $menu, only it is an index array.

Array(
	[index.php]               => dashboard
	[separator1]              => separator1
	[upload.php]              => media
	[link-manager.php]        => links
	[edit-comments.php]       => comments
	[edit.php]                => posts
	[edit.php?post_type=page] => pages
	[separator2]              => separator2
	[themes.php]              => appearance
	[plugins.php]             => plugins
	[users.php]               => users
	[tools.php]               => tools
	[options-general.php]     => settings
	[separator-last]          => separator-last
	[woocommerce]             => woocommerce
)

Version Variables

$wp_version(string)
The current version of WordPress.
$wp_db_version(number)
Current version of the database.
$tinymce_version(string)
Current version of the TinyMCE editor.
$manifest_version(string)
Cache manifest version.
$required_php_version(string)
The minimum version of PHP, which is required for the current WordPress.
$required_mysql_version(string)
The minimum MySQL version required for the current WordPress.

Browser Variables

These variables contain data about the current browser the user is using.

$is_iphone(true/false)
iPhone Safari.
$is_chrome(true/false)
Google Chrome.
$is_safari(true/false)
Safari.
$is_NS4(true/false)
Netscape 4.
$is_opera(true/false)
Opera.
$is_macIE(true/false)
Mac Internet Explorer.
$is_winIE(true/false)
Windows Internet Explorer.
$is_gecko(true/false)
FireFox.
$is_lynx(true/false)
Linux.
$is_IE(true/false)
A global variable defined by WordPress and used to determine if the current browser is Internet Explorer.
$is_edge(true/false)
Microsoft Edge.

Web Server Variables

These global variables contain data about which server WordPress is running on.

$is_apache(true/false)
Apache HTTP Server.
$is_IIS(true/false)
Microsoft Internet Information Services (IIS).
$is_iis7(true/false)
Microsoft Internet Information Services (IIS) v7.x.

Multisite

$blog_id(number)
ID of the current blog.
No comments
    Log In