WordPress - Including a variable in get_header does not work
You're running into a variable scope issue. WordPress is including the header via it's own function get_header()
and your template variables aren't available. You might find other folks recommending you just use include('header.php')
but you don't want to do that either. (get_header()
triggers other WordPress specific actions and it's important to keep it).
You have a couple of options, and one of them is my preference.
First, you can use the global
keyword to hoist your variable into the global scope like so:
global $header_choice = of_get_option( 'headerstyle', 'default' );get_header();
Then, inside header.php
you would access it again using the global keyword like so:
// from inside header.phpglobal $header_choice;if ($header_choice == 'some_option') { // do some work}
But this pollutes the global scope a bit (and it can get to be disorganized, especially if you begin using globals in other pages and for other things). So you can also scope your globals using the $GLOBALS
array and nest all of your theme's globals into their own "namespaced" array like so:
Inside functions.php
initialize your $GLOBALS
variable
// from inside functions.php$GLOBALS['THEME_NAME'] = array();
In your template file, initialize your theme options
$GLOBALS['THEME_NAME'] = array();$GLOBALS['THEME_NAME']['header_choice'] = of_get_option( 'headerstyle', 'default' );get_header();
In your header.php
file you access it simply like so:
// from inside header.phpif ($GLOBALS['THEME_NAME']['header_choice'] == 'some_option') { // do some work}