CodeTutorials

Code Estimated Read Time In WordPress With PHP

Written By 2 min read

It isn’t anything new but those tiny read time estimations for blog articles have really grown on me. And since WordPress doesn’t offer this feature out of the box, let’s build it from scratch.

Now let me start off by saying yes, there is a plugin for this. But the amount of PHP code needed really wouldn’t be worth an entire plugin.

But because this is the internet, allow me to list off a couple plugins if that is what you were after:

And there we go. For you plugin lovers, we have a small list for you to get started. But for those of you wanting a solution you can customize to your hearts content, let’s start coding.

The Main Function

Find your ‘functions.php’ file and add the following code snippet:

function estimated_read_time() {
    // Retrieve the post content
    $content = get_post_field( 'post_content', $post->ID );
    // Count the words found in the post
    $word_count = str_word_count( strip_tags( $content ) );
    // Average adult reads 238 words per minute
    $readtime = ceil($word_count / 250); 
    // Concat the calculated result with the minute unit
    $readtimestr = $readingtime . " min read"; 
    
    // Return the $readtimestr for your post loop
    return $totalreadingtime; 
}

Inserting The ‘Read Time’ To Your Theme

Pretty simple right? And once the ‘estimated_read_time()’ function has been added, you can then retrieve the read time by calling the function inside the post loop.

if (have_posts()) : 
    while (have_posts()) : 
        the_post();
        // Awesome article layout
        read_time(); // Will output 'x min read'
        // More awesome article layout
    endwhile;
endif;

And here is a quick explanation of what our PHP code snippet does:

  • First locate the post by the provided post ID.
  • Strip the HTML and formatting to count the words.
  • Divide the word count by 250 (the average adult reads 238 words a minute) and then round the result to the nearest integer.
  • Return the estimated minutes.

And there we have it. A simple function to calculate the estimated read time to a WordPress post. And it doesn’t have to end there. We can re-use this post for pages and custom post types because they have access to ‘the_content()’ function.

Anyway, thank you for reading and I hope this helps you on your WordPress journey!

Leave a Comment

* Your email address will not be published and will remain private.