1

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

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

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
  • Cheers @Bainternet didnt realise that I would need to declare it as a global but makes alot of sense. I do not seem to need to globalize it twice. Is it recommended to do this? – noelmcg Apr 3 '12 at 13:04
  • the first time is to declare it as a global and the second is for each time its not in the scope (like inside a function). – Bainternet Apr 3 '12 at 13:11
  • Okey doke, cheers @Bainternet – noelmcg Apr 3 '12 at 13:23
0

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";     
} 
  • Hi @Geert, I cant seem to get this technique working correctly. When I declare the global variable as above it doesn't work? – noelmcg Apr 3 '12 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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