There’s a growing trend for adding reading times to blog posts and articles; the idea being that, if visitors know in advance how long something takes to read, they’re more likely to read it.

That means better engagement, reduced bounce rates, etc., so naturally, the SEO community are paying attention. There’s a good summary of the evidence for all this at Marketing Land.

Calculating reading time estimates

As luck would have it, Brian Cray (mentioned in the Marketing Land article linked above) shared his PHP solution to estimating reading time back in 2010. All you need to do is paste that code into your blog’s template and you’re done – no need for another plugin to slow down your site.

But I wanted to muck about with it a bit. Brian’s solution gives a very precise answer, like “Estimated reading time: 4 minutes, 36 seconds”. I wanted something more… human.

Giving the maths some personality

I wanted my estimates to look like this: “About 2 minutes to read”. Or, if less than a minute: “Less than a minute to read”.

So here’s what I did. First, I put Brian’s code in its own file, read-time.php and saved it to the main theme folder. The only reason for this is that my templates are already crowded, so I wanted to keep things tidy.

Next, I modified Brian’s code to report only the minutes, but still count the seconds. Dispensing with seconds entirely would mean a figure of 3 minutes and 59 seconds would be reported as 3 minutes — not very helpful — so I wanted to round up or down. Doing that properly got a bit too involved, so I decided to simple add 1 to the number of minutes ($m) if seconds ($s) is 30 or more.

<?php
$mycontent = $post->post_content;
$word = str_word_count(strip_tags($mycontent));
$m = floor($word / 200); $s = floor($word % 200 / (200 / 60));
if ($s >= 30) {
$m = ($m + 1);
}
$est = $m . ' minute' . ($m == 1 ? '' : 's'); ?> 

In the WordPress template for blog posts (usually single.php, if you’re following along at home), I add a simple if else statement.

<?php include 'read-time.php'; 
if ($est >= 1) { echo 'About ' , $est , ' to read'; } 
else { echo 'Less than a minute to read'; } 
?>

That calls my modified version of the calculator, then checks to see if the result of the calculation ($est) is equal to or greater than a minute. If it is, it prints “About X minute(s) to read”; otherwise, it prints “Less than a minute to read”.

Outputting results

All that remains is to put a bit PHP in the template where you want the estimate to appear:

<?php if ($est >= 1)
{ echo 'About ' , $est , ' to read'; }
else { echo 'Less than a minute to read'; }
?>

If you prefer you can put the calculation code somewhere in your blog post or page template, too. It doesn’t have to be near the output code.

That’s it!