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.


  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 –

  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


    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 ?

Leave a Comment