【问题标题】:WordPress: Get all shortcodes from content fieldWordPress:从内容字段中获取所有简码
【发布时间】:2019-10-30 20:24:15
【问题描述】:

我正在使用自定义简码在我的内容中显示引导模式。问题是,<div> 破坏了内容。见这里:Output content of WordPress Shortcode in text and footer

No2 我想更改简码,只显示 Modal 的链接,并在内容后显示 modal-<div>

为此,我检查内容字段是否有短代码,如果是,我会在内容之后显示所有模式。

下面是代码: (部分来自这里:https://stackoverflow.com/a/18196564/1788961

$content = get_sub_field("textfield");
//write the begining of the shortcode
$shortcode = 'term';

$check = strpos($content,$shortcode);
if($check=== false) {
    //echo '<h1>NO Shortcode</h1>';
} else {
    //echo '<h1>HAS Shortcode</h1>';


    $str = '[term value="Term Name" id="600"][term value="Another Term" id="609"]';

    preg_match_all('~\[term value="(.+?)" id="(.+?)"]~', $str, $matches);

    var_dump($matches[2]);

    foreach($matches[2] as $match){
        echo 
            '<div class="modal fade" id="termModal_'.$match.'" tabindex="-1" role="dialog" aria-labelledby="termModal_'.$match.'_Title" aria-hidden="true">
                (rest of modal)
            </div>
        ';


    }


}

到目前为止一切正常。但现在我需要内容字段中的简码。

我不知道如何获得它们。这是我的简码:

[term value="Custom Link Title" id="123"]

我需要内容中每个短代码的 id 并将它们存储在 `$str' 变量中。

【问题讨论】:

    标签: php wordpress shortcode wordpress-shortcode


    【解决方案1】:

    这个使用preg_match()函数的方法应该可以工作:

    $id = 0;
    $matches = array();
    preg_match('#\[term(.*) id="([0-9]{1,})"(.*)\]#', $content, $matches);
    if (count($matches) > 2) {
        $id = $matches[2];
    }
    

    无论短代码属性的顺序如何,这都可以工作,但它假定您在 id 属性值周围有双引号,并且该值仅包含数字。

    【讨论】:

    • 你得到0$id?如果是这样,您确定 $content 包含短代码吗?
    • 我必须像这样使用自定义文件:get_sub_field("textfield", false, false); 否则短代码不在内容中作为代码。现在它起作用了。谢谢!
    猜你喜欢
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多