1

这是注册短代码的正确语法吗?

$field = 'sc_id';
$newfunc = function($field) { return get_option($field);};
add_shortcode($field, $newfunc);

我收集了需要将所有选项注册到简码的选项。其中一些正在工作,而另一些则没有。

更新:好的,此代码有效

$field = 'sc_id';
$newfunc = function() { return get_option($'sc_id');};
add_shortcode($field, $newfunc);

但是我有大约 20 个值需要注册短代码而且我更喜欢

[shortcode]

代替

[sc key="shortcode"]

我怎么能做到这一点?

在 7.2 php 之前,这段代码对我有用

$newfunc = create_function('', 'return get_option(' . $field . ');');
4

1 回答 1

1

这不是正确的语法。查看wordpress 文档

你可以尝试这样的事情:

$field = 'sc_id';
$newfunc = function($atts) { return get_option($atts['key']);};
add_shortcode($field, $newfunc); 

并像这样调用简码:

[sc_id key="option_key"]

编辑因为评论问题:

当您想要多个没有属性的字段的多个短代码时,您可以使用这样的想法:

$fields = array('sc_id','sc_it','sc_ib'); 
foreach($fields as $field) { 
    $newfunc = function() use($field) { 
        return get_option($field);
    }
    add_shortcode($field, $newfunc); 
}

使用use关键字,我们可以将外部范围变量传递给我们的匿名函数。

于 2019-03-09T17:27:06.913 回答