A popular detail that many sites show is the estimated reading time, usually for articles or blog posts.
In fact, it is really easy to generate this detail.
Here’s a simple PHP function that does just that.
PHP function
/**
* Calculates estimated reading time.
*
* @param string $content Content for which the reading time is calculated.
* @return int Estimated reading time in minutes.
*/
function notesontech_get_reading_time( string $content = null ) {
$word_count = str_word_count( strip_tags( $content ) );
$words_per_minute = 200;
return ceil( $word_count / $words_per_minute );
}
This function receives the content ($content
) for which we want to calculate the reading time.
It counts the number of words in this string element using the PHP’s str_word_count
function.
It then divides the number of words in the provided text by the number of words per minute we set, which gives us the estimated reading time in minutes.
From a quick Google search, it seems that the average reading speed is around 200-250 words per minute, so I set the $words_per_minute
variable to 200. Feel free to change this value to adjust the calculation.
On a WordPress site, this function can be added to the functions.php
file of the theme or to another theme configuration file if one exists.
The abbreviated version of this function (without defining the variables, which are only needed for ease of reading):
/**
* Calculates estimated reading time.
*
* @param string $content Content for which the reading time is calculated.
* @return int Estimated reading time in minutes.
*/
function notesontech_get_reading_time( string $content = null ) {
return ceil( str_word_count( strip_tags( $content ) ) / 200 );
}
Usage
To display the estimated reading time, we can add something like this to our posts:
<span><?php echo notesontech_get_reading_time( $post_content ); ?> min read</span>
Where $post_content
is a string element containing the content of the article/post.
On a WordPress site, a typical usage could be:
<span><?php echo notesontech_get_reading_time( get_the_content() ); ?> min read</span>