Thomas Hardy

WordPress Word Count Function

Since I launched my new stripped back website I have had a few emails asking how I got the word count of each post, so I have written a quick article to show you how I do it.

In my functions file I have a short function:

function word_count() {
    $content = get_post_field( 'post_content', $post->ID );
    $word_count = str_word_count( strip_tags( $content ) );
    return $word_count;
}

This function gets the post content, using the get_post_field function. It then uses the str_word_count and strip_tags functions to count the words of the content with the HTML tags removed, it then returns the count.

I then call the function whenever I want to display the word count.

echo word_count();

This is a very simple function with the sole goal of displaying the word count of the current post, but it could be expanded upon very easily.

7 Comments

  1. Esha

    Thanks for the solution..I was looking for this

  2. Ben

    Thanks for this, a really neat & simple solution! I adapted it slightly to display the approximate time it might take to read a blog post – http://bentatlow.com/blog/wordpress-reading-time-function/

  3. Remy Sheppard

    Thanks for this. Put it up on every post. Modified it a touch:

    function word_count($a) {
    $content = get_post_field( ‘post_content’, $post->ID );
    $word_count = str_word_count( strip_tags( $content ) );
    echo $word_count . $a;
    }

    Thus easily called:

    word_count(” Words were harmed in the making of this post”);

  4. Pierre

    Hi,

    thanks for this code Thomas.

    It works, but in debug mode, i then get these warnings :

    Notice: Undefined variable: post
    Notice: Trying to get property of non-object

    both in the second line of the codeā€¦

    should it be fixed ?

  5. Poonam Namdev

    Hi
    Thanks for the code,
    I came here looking for a way to show word count on the dashboard inside all post table. It would help me find those posts easily which have less content.
    Can you please help me get this.
    Thanks

  6. Michael

    Thanks!

    Your solution is better than my own, so I’m gonna use this instead. :)

  7. Jorge A Gonzalez

    Great basic functionality, but you might want to extend the article and allow sorting in the admin screen. It’s a great way to determine which posts are “thin”.

Leave a Comment