Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variables in a WordPress Plugin

I am trying to create my first WordPress plugin. Even in trying to create the install function, things are being a pain.

I want to set some global variables specific to my plugin rather than putting the literal values throughout the various functions. However, my install function does not pick up these global variables.

Here is my code so far:

$version = '1.0a';
register_activation_hook( __FILE__, 'install' );
function install() {
  global $version;
  add_option( 'test_version', $version );
}

Obviously this is pretty straight forward on my end. Any ideas what is going wrong here??

like image 953
Marshmellow1328 Avatar asked Dec 30 '22 13:12

Marshmellow1328


1 Answers

It turns out if you want a global variable for your install function, you must declare it to be global.

global $version = '1.0a';
register_activation_hook( __FILE__, 'install' );
function install() {
  global $version;
  add_option( 'test_version', $version );
}

More information can be found at the link below under the "A Note on Variable Scoping" section: http://codex.wordpress.org/Function_Reference/register_activation_hook

like image 87
Marshmellow1328 Avatar answered Jan 05 '23 01:01

Marshmellow1328