WordPress – Including a variable in get_header does not work

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:

Read More
$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?

Related posts

Leave a Reply

1 comment

  1. 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.php
    global $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.php
    if ($GLOBALS['THEME_NAME']['header_choice'] == 'some_option') {
        // do some work
    }