0

I'm initializing a variable with a value in the header.php file. I want access to that value in footer.php, but it doesn't exist upon checking. Example:

header.php

$status = true;

footer.php

var_dump( $status ); // is null

What's a best practice for doing something in footer.php, or other files if they have the same behavior.

3
  • What are you trying to accomplish? Eg. what does the $status variable do? Commented Oct 16, 2012 at 5:24
  • I have some internal testing I do based on the user, if they are logged in, authenticated, if it is the front page or other, etc... the point is it seems code you use in header.php cannot be inherited so that you can use it in footer.php in this manner. I'd like access to that without having to paste all the same code that comes up with the value in $status in footer.php too.
    – Poe
    Commented Oct 16, 2012 at 5:27
  • You should have a look at the WordPress action/filter API, codex.wordpress.org/Plugin_API.
    – Wyck
    Commented Oct 16, 2012 at 5:33

2 Answers 2

5

Avoid global variables, they could be overwritten by other code. You could use a helper function with a static internal variable instead. Sample code:

function wpse_69365_var_storage( $var = NULL )
{
    static $internal;

    if ( NULL !== $var )
    {
        $internal = $var;
    }

    return $internal;
}

// first call:
wpse_69365_var_storage( 4 );

// later call:
echo wpse_69365_var_storage(); // print 4
1
  • 1
    Nice idea on using static variable vs. global variable!
    – Anh Tran
    Commented Oct 16, 2012 at 7:56
1

Based upon @toscho snippet, here's a real life example. Assuming that you don't need to access a var directly from inside the template file.

function wpse_69365_var_storage()
{
    static $internal;

    if ( 'wp_head' === current_filter() )
    {
        if ( /* Condition is met */ )
            return $internal = 4; // Set to what you need.

        return 'default_value';
    }

    return print $internal;
}
// Call in header.php:
add_action( 'wp_head', 'wpse_69365_var_storage' );
// Call in footer.php:
add_action( 'wp_footer', 'wpse_69365_var_storage' );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.