Passing a variable via wp_head and then calling it on the page

As my question suggests I’m having difficulty creating a variable in the header, via functions.php and wp_head, and then calling that variable further down the page.

For example, in functions.php

Read More
add_action( 'wp_footer', 'add_ran_var' );

function add_ran_var () {   
    $random_variable = "1";     
} 

And before the

</head> 

tag include

<?php wp_head(); ?>

in header.php

The problem arises if i try to call $random_variable later on in the page. It returns nothing.

<?php echo $random_variable; ?>

Could anyone please shed some light as to why this does not work? Has it something to do with the order the different files (header.php, functions.php) are called?

Thanks in advance to anyone who can offer me some advice on the above.

Cheers
Noel

Related posts

Leave a Reply

2 comments

  1. Before you use your $random_variable for the first time you need to globalize it , something like:

    global $random_variable;
    

    then next time or any time you want to access it just call globalize it again and it will be available like this:

    global $random_variable;
    //do stuff with it
    
  2. A variable defined in a function is only accessible within that function. This is the case for your $random_variable. You could use a global variable instead.

    function add_ran_var () {   
        $GLOBALS['random_variable'] = "1";     
    }