First plugin, basic question… I am trying to print the variable $xavi
from a plugin into a theme like this:
add_action('init', '_load_options');
function _load_options() {
global $xavi;
}
So that I can use it in a theme file like this:
<?=$xavi;?>
It doesn’t look like init
is the right action hook for this but the only other one that makes sense is wp_head
and doesn’t work either
Any ideas which hook should I use or how should I define variables (maybe through an existing WP function/method instead of creating one from scratch)?
Thanks!
Your webhost has disabled
register_globals
in the php.ini, so you have to “register” your variables manually everytime you want to use it. For example:Another approach is using the
$GLOBALS
array:But in my opinion, you should avoid using globals. Instead use a simple registry-class, which you can add/get your values.
EDIT
This isn’t a WordPress specific solution and could be a bit of an overkill for this simple question. The registry pattern is an official programming design-pattern. Same goes for the singleton-pattern which I’ve used here too.
What we do here is to store our content in a registry-object. It’s singleton, so only one instance is created.
I know, the problem isn’t solved really. Instead of using the $GLOBALS array, we are using a registry class which is indeed also “global” as we call the instance everytime we need it. You don’t have control, where you call it. Also the testing of a singleton class could be problematic. If you want more control, just look at the factory-pattern with dependancy injection.
In your plugin/theme, you only have to return the instance and you’re ready to use it:
Another option would be to use a shortcode. The Wodrpess Codex talks through all the specifics. But basically setup a function that returns your variable. Add the shortcode to wordpress, then call
do_shortcode( '[shortcode]' )
inside your PHP code and you can echo it or store it to process it more. You can use use the shortcode inside content.You can use functions in themes. If I’m correct you can add the following in your template:
Should work. However the _ probably means that it’s private, so you might need to make the function public.
Inside your plugin
Then print the variable to your template/theme
my source: https://gist.github.com/aahan/7444046