1

I think I'm getting really confused with return'ing and echo'ing variables.

I've got this gravity forms hook from their support...

add_filter('gform_field_value_facebook_name', 'my_custom_population_function');
function my_custom_population_function($value){
    return 'boom!';
}

This works and returns 'boom!' as my form field default variable.

This is pretty straight forward for a general text string, but I am trying to return a PHP variable instead.

I am loading the facebook PHP SDK in my functions.php at a higher scope than the gravity form hook. The facebook SDK definitely works, for example I am currently echoing this in my wordpress theme files...

echo $userData['name']


But my question is, why does it not work if I try and return the above variable inside the gravity for hook?

Please see what I have tried below, but it returns nothing...

add_filter('gform_field_value_facebook_name', 'my_custom_population_function');
function my_custom_population_function($value){
    return $userData['name'];
}


I've also tried something similar in my wordpress functions.php, when trying to echo a variable in a filter...

$fb_app_id      = '12345678910';

// APP ID FILTER
add_action( 'fb_app_id', 'echo_fb_app_id' );
function echo_fb_app_id() {
    echo $fb_app_id;
}

But this returns nothing and the scope is the same.

Can anyone please enlighten me to why I can't pass these variables around. I think thats the technical term. Thank you very much.

1 Answer 1

3

This is because in PHP, functions don't read global variables without the global keyword.

$fb_app_id      = '12345678910';

// APP ID FILTER
add_action( 'fb_app_id', 'echo_fb_app_id' );
function echo_fb_app_id() {
    global $fb_app_id; // tells PHP to use the global variable
    echo $fb_app_id;
}

Try to add global $userData; to your my_custom_population_function.

Sign up to request clarification or add additional context in comments.

3 Comments

or like this $GLOBALS['fb_app_id']
Massive thank you @Rocket - both of your solutions worked - I think I'm getting javascript scope mixed up with how php uses higher variables.
@Joshc: Yeah, this would've worked in JavaScript. PHP's slightly different.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.