Skip to content

Localised Estimated Reading Time

So a few people have been writing about my estimated reading time function recently. In particular – it got mentioned on WPTavern in a post all about adding an Estimated Reading Time to your theme.

Then I got this tweet:

Localisation

Any time you develop anything for WordPress (that will be used publicly) you should make sure it is fully localised. By that – I mean it should make use of the localisation functionality to allow other people to translate it into their language.

So – I decided to revisit the code and make sure it’s fully translatable.

For anyone who is interested in localising WordPress themes or plugins – there’s a comprehensive document on i18n (internationalization) on the Codex.

When writing the code originally I had considered localisation, but couldn’t see a clean way to do it since it involved multiple plurals (minute, minutes and second, seconds) so to do properly would need quite a few if then statements making things more complex than should be necessary. Having thought about it further I think the easiest solution is to change the text being displayed so that it is simpler – thus needing less text.

I have ended up with the following:

/**
 * Estimate time required to read the article
 *
 * @return string
 */
function kent_estimated_reading_time() {

    $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 = sprintf( _n( '%d minute', '%d minutes', $minutes, 'kent' ), $minutes );
    } else {
        $estimated_time = sprintf( _n( '%d second', '%d seconds', $seconds, 'kent' ), $seconds );
    }

    return $estimated_time;

}

Ben View All

Ben is a lifelong Nintendo fan who also likes to build websites, and develop games. He also buys way too much Lego.

One thought on “Localised Estimated Reading Time Leave a comment

  1. Initially when I saw the estimated time on your site, I thought you manually put a rough figure. Now I feel like how stupid I was (hope no one else reads it he he)

Leave a Reply

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