in wordpress , i set a variable in header.php
<?php
$var= 'anything'
?>
but in footer.php when I echo it
<?php
echo $var;
?>
I got no thing printed ... why !>
in wordpress , i set a variable in header.php
<?php
$var= 'anything'
?>
but in footer.php when I echo it
<?php
echo $var;
?>
I got no thing printed ... why !>
I know this is a bit old question and with a solution voted but I though I should share another option and just found a better solution (that works) without using Globals
You're not in the same scope, as the header and footer files are included in a function's body. So you are declaring a local variable, and referring to another local variable (from another function).
So just declare your variable as global:
Then:
In wordpress Header, any template, Footer is different functions so you have to declare any varible as a global variable then you can access it .
I know you've already accepted the answer to this question; however, I think there's a much better approach to the variable scope problem than passing vars into the
$GLOBALS
array.Take the
functions.php
file in your theme for example. This file is included outside the scope of theget_header()
andget_footer()
functions. In fact it supersedes anything else you might be doing in your theme (and I believe in the plugin scope as well--though I'd have to check that.)If you want to set a variable that you'd like to use in your header/footer files, you should do it in your functions.php file rather than polluting $GLOBALS array. If you have more variables that you want to sure, consider using a basic Registry object with getters/setters. This way your variables will be better encapsulated in a scope you can control.
Registry
Here's a sample
Registry
class to get you started if:Save this class in your theme somewhere, e.g.
/classes/registry.class.php
Include the file at the top of yourfunctions.php
file: include( get_template_directory() . '/classes/registry.class.php');Example Usage
Storing variables:
Retrieving variables:
The registry will accept any variable type.
Note: I normally use SplObjectStorage as the internal datastore, but I've swapped it out for a regular ole array for this case.
try this code
first define your initial variable
then use the $_GLOBALS
and finally use the global variable in anywhere you want
define string inside the $_GLOBALS as taken as global variable name or use the $_GLOBALS['myvar'] direct into the code without using the global