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:
Hey @binarymoon – Just read “WordPress – Estimated Reading Time” and I think you should not forget i18n in the code”.
— Christian Zumbrunnen (@chzumbrunnen) July 3, 2014
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;
}
How was it for you? Let me know on BlueSky or Mastodon
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.