php - 只返回帖子的简码?

标签 php wordpress

是否可以从帖子中仅过滤掉简码然后运行简码?

我的页面是这样的:

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

This here is the summary

[/summary]

Lots of text here...

我只想在特定页面上显示简码。

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

$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;

有什么想法吗?

编辑:

找到一个临时解决方案。

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;

我看到 wordpress 有剥离短代码的功能,但没有剥离内容的功能。所以我从整个帖子中替换了剥离的内容字符串以获取简码。唯一的缺点是简码必须在帖子的开头。

最佳答案

更好的答案是:

$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);
}

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

关于php - 只返回帖子的简码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290810/

相关文章:

javascript - cakephp中Js文件放在哪里

php - 查询从 postman 和 phpmyadmin 运行,但不是从 android 运行

php - 我需要通过代理,(从正在运行的 fsockopen 代码获取远程视频文件的大小)

WordPress 新手需要帮助入门

wordpress - 如何定位 WordPress Functions.php 中的特定页面?

php - 登录背景更改

php - 如何使用另一个 API 的用户群在 Laravel 中设置身份验证?

javascript - 在 React 中递归渲染嵌套数据

javascript - YouTube 嵌入 WordPress - 高度问题

php - 将类别描述移至 Wordpress 页面底部