The best way to use variables on all WordPress pages The best way to use variables on all WordPress pages wordpress wordpress

The best way to use variables on all WordPress pages


The best way for this is to define all the variables explicitly in functions.php or in main plugin file for plugin. I have verified this is the way most popular plugins including akismet use. Specifically you need to do this.

define( MYVAR_TV, $options['tv'] );define( MYVAR_MOVIES, $options['movies'] );define( MYVAR_PRINT, $options['print'] );

After these you can just use them whereever you want like

echo MYVAR_TV;

Hope it helps.


It's fine to use global, but it's not encouraged (you can read more here Are global variables in PHP considered bad practice? If so, why?). You may consider Singleton implementation:

<?phpclass GlobalVariable {    /**     * @var array     */    public static $option = [];}// You can set the variable using this wayGlobalVariable::$option['movies'] = 1;// And get the variables using that arrayprint_r(GlobalVariable::$option);

Hope this can help you.


What about creating a function in functions.php that returns an array of your variables?

Example: $options = get_my_custom_vars();