简体   繁体   English

如何通过WP过滤器向Gravity Forms提交外部变量

[英]How to submit an outside variable to Gravity Forms through WP filter

This type of work is new to me, so please be patient if the answer is something easy. 这类工作对我来说是新手,所以如果答案很简单,请耐心等待。

I'm using Wordpress and Gravity Forms on my site, and I want to pre-populate the form with data from an object (the object comes from an API, so I can't just use wordpress current_user object). 我在网站上使用的是Wordpress和Gravity表单,并且希望使用来自对象的数据(该对象来自API,因此我不能只使用wordpress current_user对象)来预先填充表单。

How can I use an outside variable inside a wordpress filter? 如何在wordpress过滤器中使用外部变量?

For Example: 例如:

$fname = $object->first_name;
add_filter('gform_field_value_firstname', *Populate the field with $fname*);

The below is the normal usage of the function, from Gravity Forms Docs ( http://www.gravityhelp.com/documentation/page/Gform_field_value_$parameter_name ) 以下是Gravity Forms Docs( http://www.gravityhelp.com/documentation/page/Gform_field_value_$parameter_name )中函数的正常用法

add_filter('gform_field_value_firstname', "dothis");

Where "dothis" points to a function. “ dothis”指向功能的地方。

The below also works (based on this excellent article: http://www.doitwithwp.com/pre-populate-fields-using-gravity-forms/ ): 以下内容也可以使用(基于这篇出色的文章: http : //www.doitwithwp.com/pre-populate-fields-using-gravity-forms/ ):

add_filter('gform_field_value_firstname', create_function("", 'return "John";' ));

However, I can't figure out how to get it to accept an outside variable also. 但是,我不知道如何使它也接受外部变量。 For example, I'd like to do: 例如,我想做:

$fname = $object->first_name;
add_filter('gform_field_value_firstname', create_function("", 'return $fname;' ));

But php tells me that fname is an undefined variable. 但是php告诉我fname是未定义的变量。

I've reviewed this thread PHP: How to make variable visible in create_function()? 我已经审查了该线程PHP:如何使变量在create_function()中可见? , but I could not get the Closure solutions to work. ,但我无法使用Closure解决方案。 I have PHP Version 5.2.17. 我有PHP版本5.2.17。

Would you please post an example of how to do this correctly? 您能否发布一个正确执行此操作的示例?

Make $fname a global variable and you can reference it in your create_function as a global. $fname设为全局变量,然后可以在create_function中将其作为全局变量引用。

global $fname = $object->first_name;
add_filter( 'gform_field_value_firstname', create_function( '', 'global $fname; return $fname;' ) );

However if you have multiple values to return, it's better to make $object global: 但是,如果有多个值要返回,则最好使$ object为全局变量:

global $object;
add_filter( 'gform_field_value_firstname', create_function( '', 'global $object; return 
$object->first_name;' ));
add_filter( 'gform_field_value_lastname', create_function( '', 'global $object; return $object->last_name;' ));

And so on... 等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM