Following on from the post for How to create a reading timer from Advanced custom fields content, I thought I’d share how to create the same thing but for the standard WordPress content. So, here is a little function that calculates the average reading time based upon the post content.
Working out the reading time
First, place this within your theme or child/custom theme’s functions file.
// Reading time calculator
function reading_time($the_post_ID) {
// get the content
$the_content = get_post_field( 'post_content', $the_post_ID );
// count the number of words
$words = str_word_count( strip_tags( $the_content ) );
// calculate reading time based on number of words
// divided by 200 - average words read per minute
$readingtime = ceil($words / 200);
if ($readingtime <= 1) { // If the reading time is equal to or less than 1
$timer = " minute";
} else {
$timer = " minute";
}
if ($readingtime == 0) { // if the reading time equals 0 then change it to 1
$totalreadingtime = "1" . $timer . " read";
} else {
$totalreadingtime = $readingtime . $timer . " read";
}
return $totalreadingtime;
}
Display the reading time
To display the reading time within your template files use this snippet.
// Display the reading time // Wrap this in the HTML tag of your liking echo reading_time(get_the_ID());
If you like this post then you might like this one too.
How to create a reading timer from ACF Pro flexible content