The PHP function
Copy the following PHP code snippet to your functions.php file:
//Calculate the Estimated reading time of any page or post
function site_estimated_reading_time( $content = '', $wpm = 250 ) {
$clean_content = strip_shortcodes( $content );
$clean_content = strip_tags( $clean_content );
$word_count = str_word_count( $clean_content );
$time = ceil( $word_count / $wpm );
return $time;
}
This function takes the average number of words adults read per minute as a value. According to Iris Reading, the average reading speed of most adults is around 200 to 250 words per minute. College students are faster readers at around 300 words per minute.
The rest of the function is quite easy to follow:
- First, the function cleans the content from any shortcodes and HTML tags that should not be counted.
- Then the function counts the number of words in the clean content.
- The estimated reading time gets calculated by dividing the number of words by the number of words per minute.
- The function lastly returns the resulting time variable.
Inserting the function
I inserted the function into a div that I added to the after_entry_title hook, so it appears below the post title. I give the div a class named reading-time so I can easily style the text using CSS:
<div class="reading-time">
Est. reading time: <?php echo site_estimated_reading_time( get_the_content() ); ?> minutes
</div>
Styling the text
The reading time below the post title is styled like your main content. Since it’s an extra feature I don’t want to attract all the attention to, I made it look more demure by changing the color to grey and reducing the font size to 85%:
/* Styling for estimated reading time */
.reading-time {
color: #888;
font-size: 85%;
}