For some reason whenever I try to put a variable in get_header
in my custom page.php in WordPress, it doesn’t recognise the value and resets to default.
Here’s my code:
$header_choice = of_get_option( 'headerstyle', 'default' );
get_header( $header_choice );
of_get_option is a function from Options Framework
This because I’m using multisite and it would be great if power users can change the header themselves per-site without having to dive into the code or having to ask us, the developers.
How can I use a variable in get_header
so I can dynamically assign the value?
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 useinclude('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:Then, inside
header.php
you would access it again using the global keyword like so: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
variableIn your template file, initialize your theme options
In your
header.php
file you access it simply like so: