WordPress注册短代码与反义词功能

问题描述 投票:1回答: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个值我需要注册shortcodeds而我更喜欢

[shortcode]

代替

[sc key="shortcode"]

我怎么能这样做?

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

$newfunc = create_function('', 'return get_option(' . $field . ');');
php wordpress wordpress-shortcode
1个回答
1
投票

这不是正确的语法。看看wordpress docs

你可以尝试这样的事情:

$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关键字,我们可以将外部范围变量传递给我们的匿名函数。

© www.soinside.com 2019 - 2024. All rights reserved.