Make global variable in WordPress easily.

What is global variable?

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

Copy “global variable code” and paste it in your function.php file.

Global Variable Code

<?php global $my_global_variable;
$my_global_variable = 'Hello World'; // your global variable value
?>

Now you have global variable, use it inside any function or any php file in your WordPress theme.

Usage

Using your variable inside some functions, for example we will use it inside wordpress shortcode:

<?php function my_shortcode(){
global $my_global_variable;
return $my_global_variable; // now will be print "Hello World" in your post.
}
add_shortcode('my_shortcode', 'my_shortcode'); // this is your shortcode, use it in your post: [my_shortcode]
?>

Now use this shortcode [my_shortcode] in your post or page, will be display “Hello World”.

Using your variable inside some php files in your WordPress theme, for example in footer.php file:

<?php global
$my_global_variable;
echo $my_global_variable; // now will be print "Hello World" in your file.
?>

Now will be display “Hello World” in footer.