简体   繁体   中英

Counting the total number of paragraphs on a wordpress blog post

I've written a small snippet to count the total number of paragraph on any WordPress blog post so that it can return that number and based on that number I can do other stuff. But it seems not be working properly. Any anyone take a look and tell me why?

What I Want my code to return?

I want my code to return the total number of paragraphs on each blog post.

Here is my code:

//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;
    }
}

Any help will be highly appreciated.

Use PHP's regular expression matcher instead.

Something like this should do the trick:

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

An example of the Pattern: https://regex101.com/r/oE8fI7/1

More info here: http://php.net/manual/en/function.preg-match-all.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM