Why global variables don't work in WordPress template parts?
Posted on 2013-05-25
Hi WP Experts!
I am relatively new to WP and coding a template part - I am finding that global variables do not work inside the template part and can't figure out why?
For example, please see the code below. The 'echo' statement displays an empty string, not the expected 'testing' value.
$myvar = "testing";
I Googled this condition and found that if I declare the variable $myvar as a global at the top of the page (even though it's the first time I'm using it), then assign the value of 'testing', the echo statement inside the test_func() then works as expected. But why?
Can anyone explain:
1) Why I need to declare the variable as a global in this case?
2) Is there a WP setting I can make somewhere centralized so that I don't need to worry about where globals work and where they don't (basically - so I can use global vars and have them work the way I expect them to work everywhere in the WP framework?)