wordpress 插件:使用 OOP 设置 api [英] wordpress plugin : settings api with OOP
问题描述
我现在正在使用 OOP 来创建我的 wordpress 插件,但是我在设置 API 方面遇到了问题,我认为第三个参数(回调函数)应该 ECHO/PRINT 从定义的函数中返回值,而不是使函数回显输入,查看更多信息:
I am now using OOP to create my wordpress plugin, however i am having a problem with the Settings API,i think the third parameter (the callback function) should ECHO/PRINT a returned value from the defined function, and not make the function Echo the input, look at this for more informations :
这是您需要查看的代码片段:
and this is the code snippet you need to look at :
public function another_function(){
add_settings_field('test', 'test', $this->get_input('test', 'test', 'text'), 'test_settings', 'test_settings');
}
public function get_input($id, $name, $type, $size=40, $droparray = NULL){
$options = get_option('brutal_settings_group');
switch ($type) {
case 'text':
echo '<input id="'. $id .'" name="test['. $name .']" size="'. $size .'" type="text" value="'. $options[$name] .'" />';
break;
}
}
由于 get_input 函数中的回声,每个页面中的字段都打印在所有内容之上,但是如果 wordpress 函数 add_settings_field 打印了一个返回值,而不是依靠函数自行打印它,它就会起作用,那么这个怎么出来的?
because of the echo in the get_input function, the fields get printed above everything in every page, but if the wordpress function add_settings_field printed a returned value and not counted on a function to print it for it self, it would've worked,so how to out come this ?
希望我的想法很清楚,最好的问候
Hope i got my idea clear, Best Regards
推荐答案
add_settings_field
期望它的第三个参数是 callback,但您实际上是在调用您的get_input
方法.为了使用 get_input
方法作为回调,您需要传递一个包含对象和方法名称的数组 array($this, 'get_input')
.
add_settings_field
expects it's third argument to be a callback, but you are actually calling your get_input
method. In order to use the get_input
method as a callback you need to pass an array containing the object and method name array($this, 'get_input')
.
在执行此操作时,您不能将参数直接传递给方法,但我认为如果您将一组值作为第六个参数传递给您的 add_settings_field
调用 Wordpress 将依次传递此数组当它被调用时到你的回调.因此,您的 add_settings_field
调用将如下所示:
You can't pass arguments to directly to the method when doing this, but I think if you pass an array of values as the sixth argument to your add_settings_field
call Wordpress will in turn pass this array to your callback when it's called. So, your add_settings_field
call would look something like this:
add_settings_field(
'test',
'test',
array($this, 'get_input'),
'test_settings',
'test_settings',
array(
'id' => 'test',
'name' => 'test',
'type' => 'text'
)
);
然后您需要修改回调函数以从数组中提取值,如下所示.
You'd then need to modify your callback function to extract the values from the array, something like the below.
public function get_input($args) {
$size = 40;
$droparray = NULL;
extract($args);
…
这篇关于wordpress 插件:使用 OOP 设置 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!