How To Display Read Time On WordPress Articles
January 14, 2021 • PHP, WordPress • Published By Josh • 2 minute read
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!
Table of Contents
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; ?>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
}
}
?>
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;
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 ) );
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 );
All that’s left to do is output the read time!
echo $minutes . ' minute read';
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' ) && !in_category( 'projects' ) ) {
READ TIME CODE HERE...
}
?>