2 minute read

WordPress: Count the Number of Words in a Post Along with how to estimate the time to read.

I have seen a number of ways around the interwebs of counting the number of words in a Post in WordPress.  Some, in my opinion, are shockingly bad.

The most startling involves the use of output buffering (!).

This really is pretty simple in WordPress so those of you that need a function to do this, please see below.

The Way I Do It

<?php $number_of_words = str_word_count( strip_tags( get_the_content() ) ); ?>

Note:  This will work in a loop.  You are inside a loop when you want to do this though right?

Bonus: Time to Read Estimation (like medium.com)

Well, we have the number of words now, so estimating the time to read is easy.  Since the average person reads casually about 200 words per minute all we have to do is divide the number of words by 200 and take the ceiling (or floor) so we get an integer estimation.

<?php $time_to_read = ceil( $number_of_words / 200 ); ?>

Pretty simple.  There is nothing ground breaking here but I figured I would chime in since Google had such poor posts.  For all I know, there is a built-in WordPress function to do the same thing since this is displayed on the Admin side of things.

Conclusion

There are a number of things you could probably do with functions similar to what I have shown.  I think this is the most straightforward way to accomplish this and uses only built-in WordPress and PHP functions.

In general, I try to avoid output buffering.  I think a good rule-of-thumb is to not use output buffering unless you really have to.  This means to spend more then one-minute trying to think of another way to code what you are trying to accomplish.

The only exception to this is when I want to return HTML from a shortcode.  In that case I find output buffering to be a more elegant solution.


Leave a Reply

Your email address will not be published.