只返回帖子中的短代码?

Ric*_*ard 4 php wordpress

是否可以过滤掉帖子中的短代码,然后运行短代码?

我的页面看起来像这样:

[summary img="images/latest.jpg"]

This here is the summary

[/summary]

Lots of text here...
Run Code Online (Sandbox Code Playgroud)

我只是想在特定页面上显示短代码.

尝试使用正则表达式,但它们似乎不起作用:

$the_query = new WP_Query('category_name=projects&showposts=1');

    //loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<b>';
        the_title();
        echo '</b>';
        echo '<p>';

        $string = get_the_content();

        if (preg_match("[\\[[a-zA-Z]+\\][a-zA-Z ]*\\[\/[a-zA-Z]+\\]]", $string , $matches)) {
            echo "Match was found <br />";
            echo $matches[0];
        }

        echo '</p>';
    endwhile;
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:

找到了临时解决方案.

while ( $the_query->have_posts() ) : $the_query->the_post();

    $content = str_replace(strip_shortcodes(get_the_content()),"",get_the_content());               
    echo do_shortcode($content);

endwhile;
Run Code Online (Sandbox Code Playgroud)

我看到wordpress有一个用于条带化短代码但不用于条带内容的功能.所以我从整个帖子中删除了剥离的内容字符串以获得短代码.关于这一点的唯一不好的是,短代码必须在帖子的开头.

two*_*ash 13

更好的答案是:

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'the_shortcode_name') {
   $shortcode = $matches[0];
   echo do_shortcode($shortcode);
}
Run Code Online (Sandbox Code Playgroud)

它将在帖子内容中搜索名为"the_shortcode_name"的短代码.如果找到它,它会将短代码存储在$ matches变量中.很容易从那里运行它.