Logo
Logo
Wordpress function

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.

Matt

Matt has been working in the web industry for over 15 years, he is also an avid mountain biker. He discovered his love for the internet years ago and has since honed his skills to keep up with the latest trends and technologies in the industry. Matt has worked with a diverse range of clients, including small businesses, non-profits, and large corporations, delivering high-quality websites. Apart from his work, Matt loves to explore the outdoors and takes every opportunity to hit the trails on his mountain bike. His commitment to his work and passion for mountain biking have earned him a reputation as a talented and well-rounded individual. If you're in need of a skilled web developer or an adventure-seeking mountain biker, Matt is the perfect fit.