How To Display Read Time On WordPress Articles

nightwolfdev - Jan 15 '21 - - Dev Community

Time is important to all of us yet we can never seem to find enough time in the day! When you’re browsing the web, you’ll probably read articles that won’t take up as much of your time at that moment. Displaying read time can be helpful to your visitors and even make them stay on your site longer. Let’s learn how to display read time!

Find The Loop

You need to find the WordPress loop code in each of the theme files you’d like to display your read time. Every theme is different, but you should be able to find something similar to the examples below:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php endwhile; else : ?>

<?php endif; ?>
Enter fullscreen mode Exit fullscreen mode
<?php 
  if ( have_posts() ) {
    while ( have_posts() ) {
      the_post(); 

    } 
  } 
?>
Enter fullscreen mode Exit fullscreen mode

Here are some common theme files where you may want to display the read time in the WordPress loop:

  • category.php
  • index.php
  • search.php
  • single.php
  • tag.php

Read Time

Let’s get the content of the article first. Because you’re in the WordPress loop, you can grab the content from the $post variable using the post_content property.

$content = $post->post_content;
Enter fullscreen mode Exit fullscreen mode

Remove any HTML and PHP tags using the strip_tags function. Count how many words there are using the str_word_count function.

$words = str_word_count( strip_tags( $content ) );
Enter fullscreen mode Exit fullscreen mode

Now the calculation for the read time in minutes. An average read time is 200 words per minute. Divide the number of words by 200 and then round up using the ceil function.

$minutes = ceil( $words / 200 );
Enter fullscreen mode Exit fullscreen mode

All that’s left to do is output the read time!

echo $minutes . ' minute read';
Enter fullscreen mode Exit fullscreen mode

Conditional Display

What if you didn’t want to display the read time for specific categories. You can wrap the code in an IF statement checking against the category using functions like is_category and in_category.

For example, if you’re in the index.php template, you can use the following to only display the read time if the category is NOT projects:

<?php 
  if ( !is_category( 'projects' ) &amp;&amp; !in_category( 'projects' ) ) { 
    READ TIME CODE HERE...
  }
?>
Enter fullscreen mode Exit fullscreen mode

Visit our website at https://nightwolf.dev and follow us on Facebook and Twitter!


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .