Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to use variables on all WordPress pages

I'm building a custom theme that has a lot of variables that I wish to use throughout.

Example:

$tv     = $options['tv'];
$movies = $options['movies'];
$print  = $options['print'];
//....and about 50 more.

For this purpose I have been simply placing them all in a file called vars.php and then in header.php of the theme I include it...

require_once('vars.php');

While this does work, it doesn't feel like the best way. I've read on numerous occasions that use global variables (presumably in functions.php) isn't a good idea, but is this true?

But if it's fine to use global variables in functions.php (even lots of them) is this the right way to go about it?:

global $tv;
$tv     = $options['tv'];

global $movies
$movies = $options['movies'];

global $print
$print  = $options['print'];
like image 485
User_FTW Avatar asked Sep 15 '17 23:09

User_FTW


People also ask

What are WordPress global variables?

What Are WordPress Global Variables? A WordPress global variable is a variable that holds information generated by the application. These global variables can be accessed during the execution of the application and during the page life cycle.

Where are WordPress variables stored?

WordPress stores its environment variables in its wp-config. php file. Since this file is required for WordPress to operate, it's common for it to be committed to code repositories along with the rest of the site code.


1 Answers

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.

like image 102
shazyriver Avatar answered Nov 16 '22 00:11

shazyriver