Creating a custom reading time calculator for your WordPress blog
You will require the use of PHP and JavaScript in order to determine the reading time of a blog article in WordPress.
First, add a new PHP function to the functions.php file of your theme. Based on the post’s word count, this function will determine how long it will take to read the post.
function calculate_reading_time() {
global $post;
$content = $post->post_content;
$word_count = str_word_count( strip_tags( $content ) );
$reading_time = ceil( $word_count / 200 );
return $reading_time;
}
This code accesses the post’s content using the global $post variable, and then counts the post’s words using the PHP str word count() and strip tags() methods. The reading time in minutes is then calculated by dividing the word count by 200 (the average reading speed) and rounding up to the next whole number.
This method must then be called in your single.php file in order to display the reading time on the post.
<div class="reading-time">
<?php echo calculate_reading_time(); ?> min read
</div>
Use the aria-label attribute on the div with the value “Reading time: [calculated time] minutes” to make this accessible.
<div class="reading-time" aria-label="Reading time: <?php echo calculate_reading_time(); ?> minutes">
<?php echo calculate_reading_time(); ?> min read
</div>
In order to style it differently, you can use JavaScript to add a class to the post’s body if the reading time is under a predetermined threshold.
<script>
var time = "<?php echo calculate_reading_time(); ?>";
if (time < 5) {
document.body.classList.add("quick-read");
}
</script>
Always backup your site before making any code changes or changes to functions.php.
If the reading time is under five minutes, a “quick-read” class will be added to the post’s body> element.
To ensure accessibility, test the code on several platforms and screen readers.