How to Make a Reading Time Calculator for WordPress with PHP

I wrote a quick how-to guide of generating a reading time calculator for your Statamic website a few weeks ago, and I wanted to share how to accomplish the same thing on the biggest platform in the world, WordPress.

There are certainly plugins you can install to accomplish something similar, but I like doing as much as possible myself, and throwing this together is not to difficult.

First up, you need to add a function to the functions.php file in your theme’s folder. The exact function I’m using is this:

Updated Jan 31, 2016: Made it smarter so that it returns “minute” or “minutes” depending on the calculated time.

function reading_time() {
    $content = get_post_field( 'post_content', $post->ID );
    $word_count = str_word_count( strip_tags( $content ) );
    $readingtime = ceil($word_count / 200);

    if ($readingtime == 1) {
      $timer = " minute";
    } else {
      $timer = " minutes";
    }
    $totalreadingtime = $readingtime . $timer;

    return $totalreadingtime;
}

Essentially, this takes each entry, strips all the code tags and extraneous text, and gets a word count. Then it divides by 200, which is a pretty average reading speed, and rounds that to the next highest number.

Then you need to call this function to display on your site, and you can put it anywhere. I have mine in the entry-meta.php file so it displays with the author and date information on each post.

<?php echo reading_time(); ?>

This returns just a number, so you’ll have to add any context around it in your HTML to put it in context.