1

我有一个插件的简码,我无法修改...这个简码有一些参数。[some_shortcode value=""] - 我尝试输入来自 post meta 的值作为此简码的参数,但它不起作用 - 这是代码...

这是我创建的短代码的代码(它从 post meta 返回值)

function test_shortcode( $string ) {
    extract( shortcode_atts( array(
        'string' => 'string'
    ), $string));

    // check what type user entered
    switch ( $string ) {
        case 'first':
            return get_post_meta( get_the_ID(), 'post_meta_one', true );
            break;
        case 'second':
            return get_post_meta( get_the_ID(), 'post_meta_two', true );
            break;
    }
}
add_shortcode('test', 'test_shortcode');

现在我想将此短代码插入我页面上插件的现有短代码中。

For example: [some_shortcode value='[test string="first"]']

它不是这样工作的。感谢帮助!

4

1 回答 1

2

像您提供的那样在现有的简码中插入简码是行不通的。您的简码应该有机会将提供的简码作为属性处理。

您应该do_shortcode()在您的简码中使用。你有

[some_shortcode value='[test string="first"]']

并希望使用您的简码中的返回[test string="first"]first。您的代码将是:

function some_shortcode($atts){
    $atts = shortcode_atts(array(
        'value' => ''
    ), $atts);

    $second_shortcode_value = do_shortcode($atts['value']);

    //some code

    return $something;
}
add_shortcode('some_shortcode', 'some_shortcode');

该变量$second_shortcode_value将包含简码的输出[test string="first"]

PS 避免使用exctract()函数,因为它会使您的代码难以阅读

编辑:

这是将属性动态添加到[some_shortcode] value属性的解决方案。

function my_shortcode($atts){
    $atts = shortcode_atts(array(
        'str' => ''
    ), $atts);


    switch ( $atts['str'] ) {
        case 'first':
            $modified = get_post_meta( get_the_ID(), 'leweb_gender', true );
            break;
        default:
            $modified = '';
    }

    if(!empty($modified)) {
        $second_shortcode_with_value = do_shortcode("[some_shortcode value='$modified']");
    }else{
        $second_shortcode_with_value = do_shortcode('[some_shortcode]');
    }

    return $second_shortcode_with_value;
}
add_shortcode('some_shrt', 'my_shortcode');

我们在做什么:我们不是调用[some_shortcode value='something'],而是生成something我们的短代码并获取类似的内容

[some_shrt str="first"] 
于 2018-03-27T22:35:32.377 回答