How to add reading time to your blog posts with no plugin

Posted on:

Why add reading time to blog posts?

If you are an avid reader, I’m sure you’ve seen blog posts that show an estimated reading time. Knowing how long it takes to read an article encourages your website visitor to stick around. This helps to build your user engagement and increase your website conversions.

I find having a reading time helps me decide if I should read the article right away or bookmark it for another time.

How to calculate reading time?

According to the Free Reading Test, adults read about 200-300 words per minute(WPM).

To get an estimated reading time for the blog post, we need to first find out the number of words in our blog post. Then divide that number by the WPM we set for our website users.

Let me give you an example. Last week I wrote a blog post about the things developers should do before launching a WordPress website. According to the Gutenberg editor, this post has 2175 words.

I have set a WPM count of 200 for my website. So my estimated reading time for this blog post would be 2175/200 which is about 11 minutes.

How to code the reading time calculation in PHP.

In your theme folder, go to the functions.php and add the following code.

function femscores_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 = " min";
	} else {
		$timer = " mins";
	}
	$totalreadingtime = $readingtime . $timer;
	return $totalreadingtime;
}

How to display the reading time in your PHP file.

In the WordPress PHP file where you want to display the reading time add the following code.

<?php echo femscores_reading_time() .' read'; ?>

In my case, I added the code to display the reading time in my content.php file.

 <div class="entry-meta">
<h6 class="posted-on"><?php femscores_posted_on();  ?> . <?php echo femscores_reading_time() .' read'; ?>
</div>

This will add the reading time in mins. To add a bit of context around, I added the text ‘read’ next to it. I wrapped it up inside the h6 tag that was displaying the blog post date.

Notes:

You can also use a plugin called Reading Time WP that calculates the estimated reading time. You can add it to your post before the content of the post or before the excerpt depending on how you set it up. You can also use shortcodes to display it anywhere on the page.