How to Set and Access Global Variables in WordPress
Is it possible to set a variable and access it from anywhere in a PHP file in WordPress?
In WordPress, you can set a global variable using the $GLOBALS array or define it in a common file like functions.php. Here's how you can do it:
1. Using $GLOBALS Array
You can store a variable globally using $GLOBALS and access it from any PHP file in your theme or plugin.
Set Global Variable (in functions.php or any common file)
$GLOBALS['my_global_variable'] = 'Hello, WordPress!';
Access Global Variable (anywhere in WordPress)
echo $GLOBALS['my_global_variable']; // Outputs: Hello, WordPress!
2. Using define() (for Constants)
If you need a constant value that doesn’t change, use define().
Set a Global Constant (in functions.php)
define('MY_GLOBAL_CONSTANT', 'Hello, WordPress!');
Access the Constant (anywhere in WordPress)
echo MY_GLOBAL_CONSTANT; // Outputs: Hello, WordPress!
3. Using a Global Function
If you want better encapsulation, create a function in functions.php to return the global variable. Define a Function (in functions.php)function get_my_global_variable() { return 'Hello, WordPress!'; }
Access the Function (anywhere in WordPress)
echo get_my_global_variable(); // Outputs: Hello, WordPress!
4. Using WordPress Hooks (wp or init)
You can set a global variable during WordPress initialization.
Set Global Variable (in functions.php)add_action('init', function() { global $my_global_variable; $my_global_variable = 'Hello, WordPress!'; });
Access Global Variable (anywhere in WordPress)
global $my_global_variable; echo $my_global_variable; // Outputs: Hello, WordPress!
Best Practice Recommendation
- Use constants (define()) for fixed values.
- Use global variables ($GLOBALS) for site-wide values.
- Use functions (get_my_global_variable()) for better control.
- Use hooks (init) for variables dependent on WordPress execution.