计算wordpress博客帖子

时间:2016-08-26 21:52:14

标签: php wordpress

我已经写了一个小片段来计算任何WordPress博客文章中段落的总数,以便它可以返回该数字,并根据该数字我可以做其他的事情。但它似乎没有正常工作。有谁看看并告诉我为什么?

我希望我的代码返回什么内容?

我希望我的代码能够返回每篇博文上的段落总数。

这是我的代码:

//Check paragraph count on a blog post
function __check_paragraph_count_blog() {
    if ( is_singular( 'post' ) ) {
        $content = apply_filters('the_content', $post->post_content);
        $contents = explode("</p>", $content);
        $p_count = 1;
        foreach($contents as $content) {
            $p_count++;
        }

        return $p_count;
    }
}

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

使用PHP的正则表达式匹配器。

这样的事情可以解决问题:

$subject = "<p>paragraph one</p>
    <p>paragraph two</p>
    <p>paragraph three</p>
    <p>paragraph four</p>";
$pattern = "/<p>.*?<\/p>/gm"; // Global & Multiline
$paragraph_count = preg_match_all($pattern,$subject);

模式的一个例子:https://regex101.com/r/oE8fI7/1

此处有更多信息:http://php.net/manual/en/function.preg-match-all.php