kursor Creative Digital Design - Canberra
Wordpress function

Creating a custom reading time calculator for your WordPress blog

Posted by: Matt | January 23, 2023

To calculate the reading time of a blog post in WordPress, you will need to use a combination of PHP and JavaScript.

First, create a new PHP function in your theme’s functions.php file. This function will be used to calculate the reading time of a post based on the number of words in 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 function uses the global $post variable to access the post’s content, and then uses the PHP str_word_count() and strip_tags() functions to count the number of words in the post. It then divides the word count by 200 (an average reading speed) and rounds up to the nearest whole number to give the reading time in minutes.

Next, you will need to call this function in your single.php file and display the reading time on the post.

<div class="reading-time">
    <?php echo calculate_reading_time(); ?> min read
</div>

To make this accessible, you can use aria-label attribute on the div, with value “Reading time: [calculated time] minutes”

<div class="reading-time" aria-label="Reading time: <?php echo calculate_reading_time(); ?> minutes">
    <?php echo calculate_reading_time(); ?> min read
</div>

Finally, you can use JavaScript to add a class to the body of the post if the reading time is less than a certain number of minutes, so you can style it differently.

<script>
    var time = "<?php echo calculate_reading_time(); ?>";
    if (time < 5) {
        document.body.classList.add("quick-read");
    }
</script>

This will add a “quick-read” class to the <body> element of the post if the reading time is less than 5 minutes.

Note: make sure to test the code on multiple devices and screen readers to ensure accessibility.