【问题标题】:Use Shortcode in Shortcode (insert post meta field value)在简码中使用简码(插入后元字段值)
【发布时间】:2018-03-28 17:07:16
【问题描述】:

我有一个插件的简码,我无法修改...这个简码有一些参数,例如。 [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"]']

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

【问题讨论】:

    标签: wordpress shortcode post-meta


    【解决方案1】:

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

    您应该在您的简码中使用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"] 短代码的输出。

    附:避免使用exctract()函数,因为它可以make your code hard readable

    编辑:

    这是将属性动态添加到[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"] 
    

    【讨论】:

    • 这非常完美!多谢!我对你的代码做了一点改动——我直接在 switch case 中返回简码,但其余的都很棒——谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2018-08-02
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多