Joshc
Joshc

Reputation: 3853

Passing a php variable into a gravity forms hook

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.

Upvotes: 1

Views: 4894

Answers (1)

gen_Eric
gen_Eric

Reputation: 227290

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.

Upvotes: 3

Related Questions