Create a shortcode which will add estimated reading time for your articles

Estimated reading time can help your visitors calculate the time needed to read the entire article. By providing that average time, a visitor can decide to read the article right away or maybe to bookmark it and leave reading for some other time if the article was long for them at the moment.

We already showed you two simple plugins which can help you create estimated reading time labels. But in case you want to do it yourself, you don’t have to install any plugins – you can create your own function and a simple shortcode for it:

  1. Copy and paste the following code in your functions.php
function wploop_ert() {
    $post = get_post();
    $words = str_word_count( strip_tags( $post->post_content ) );
    $minutes = floor( $words / 120 );
    $seconds = floor( $words % 120 / ( 120 / 60 ) );
    
    if ( 1 <= $minutes ) {
   		$estimated_time = $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ', ' . $seconds . ' second' . ($seconds == 1 ? '' : 's');
    } else {
    	$estimated_time = $seconds . ' second' . ($seconds == 1 ? '' : 's');
    }
    return $estimated_time;
}
add_shortcode( 'ert', 'wploop_ert' );
  1. Put [ert] shortcode where you want your estimated reading time to appear

Now, if you want to show the estimated reading time for your every post calculated by the function, you only need to paste the following snippet in your single.php file where you want it to appear:

<?php echo do_shortcode(‘[ert]’); ?>

But, you probably want estimated time to be displayed on your homepage as well where your articles are summarized. One way to do that is to find your content.php file and place the same code shown above in this file where you want it to appear.

For example, you can place the code just under meta information: <?php twentyfifteen_entry_meta(); ?>

If you do this, your estimated reading time will be show right among author’s name and date.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *