• Resolved mattyk

    (@mattyk)


    Hi

    I’ve set my theme up so that I can pass a variable to the header.php from index.php inside my theme.

    However, reading around it seems that the variable isn’t passed through to the header.php file unless I use an absolute path to it instead of get_header. Example:

    Instead of

    <?php
    $bodyid="homepage";
    ?>
    
    <?php
    get_header();
    ?>

    I use

    <?php
    $bodyid="homepage";
    ?>
    <?php include ($_SERVER['DOCUMENT_ROOT']. "/wp-content/themes/classicmodified/header.php");?>

    I’m not great with PHP and this is only my 2nd theme – could anyone tell me if there is any reason why I shouldn’t do this?

    The reason for it is I want to pass a body id and page title into the header file so it changes depending on the what page it is on. I think there is another way of doing this using conditional tags but not all my pages need to be wordpressed so I’d like to keep them as static html while getting them to still use the same header file as the wordpress pages.

    Thanks in advance!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter mattyk

    (@mattyk)

    I’ve had a bit of search around for the answer to this but I can’t find out if this is an OK thing to do or not. Could anyone give me an opinion?

    much appreciated
    M

    Moderator Samuel Wood (Otto)

    (@otto42)

    ww.wp.xz.cn Admin

    Could anyone give me an opinion?

    Directly calling it is a bad idea.

    The reason you’re not getting the variable passed has to do with scoping rules. When you call get_header(), you leave the global scope and enter the function scope. Actually, this is intentional and you shouldn’t bypass it in this way. Mainly because you don’t get any of the code in get_header() to run. While that code is currently pretty minimal, it might not always be so. Also, because having your header modify your global variables can cause unseen side effects.

    A better way is to explicitly define the variable you want to be globally used. This ensures that only the variables you specify are globally scoped. Make sure you give the variable a unique name as well, so as to avoid naming conflicts.

    So if your theme is “mytheme”, then you could do something like this:

    index.php:

    <?php
    global $mytheme_body_id;
    $mytheme_body_id = 'whatever';
    get_header();
    ?>

    header.php:

    <?php
    global $mytheme_body_id;
    echo $mytheme_body_id; // outputs "whatever"
    ?>

    Like that. Just define the variable as global before you use it and you’ll always get the same one.

    Same goes for the footer, sidebars, and comments, by the way.

    Thread Starter mattyk

    (@mattyk)

    Otto42 – thankyou so much for this. I had a nagging feeling I was storing up problems for a later date!

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Using absolute path instead of get_header to pass variable’ is closed to new replies.