According to this Medium article reading time is calculated total number of words in a post divide by 200.
Now coming straight to the point.
The initial part of the code is taken from the above-mentioned article and I give full credits to the author
How to calculate the reading time?
//Estimated reading time
function reading_time()
{
$content = get_post_field('post_content', $post->ID);
$word_count = str_word_count(strip_tags($content));
$readingtime = ceil($word_count/200);
if ($readingtime == 1)
{
$timer = " minute";
}
else
{
$timer = " minutes";
}
$totalreadingtime = $readingtime . $timer;
echo $totalreadingtime;
// Using echo here to print the time
}
How to convert it into a shortcode and use it on the single post template?
function readingtime_shortcode()
{
ob_start();
get_reading_time();
return ob_get_clean();
}
add_shortcode('Reading-time', 'readingtime_shortcode');
Full code to be placed into a .php file
<?php
//Estimated reading time
function reading_time()
{
$content = get_post_field('post_content', $post->ID);
$word_count = str_word_count(strip_tags($content));
$readingtime = ceil($word_count/200);
if ($readingtime == 1)
{
$timer = " minute";
}
else
{
$timer = " minutes";
}
$totalreadingtime = $readingtime . $timer;
echo $totalreadingtime;
// Using echo to print the time
}
wp_reset_postdata();
// Creating a shortcode
function readingtime_shortcode()
{
ob_start();
get_reading_time();
return ob_get_clean();
}
add_shortcode('Reading-time', 'readingtime_shortcode');
Where to use a shortcode?
You can use the shortcode at any location you want to display the time.
How I have added and where I have put –
