Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@andrearufo
Last active January 21, 2021 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrearufo/7a969e0c50f81686d44a834ab1c5bcbe to your computer and use it in GitHub Desktop.
Save andrearufo/7a969e0c50f81686d44a834ab1c5bcbe to your computer and use it in GitHub Desktop.
A simple function to calculate the estimate reading time of a Wordpress post (article or page or custom post). Easy to use inside the loop code.
<?php
/**
* Return the string with infos
* about the reading time of the post
*
* @return String computed reading time
*
* @author Andrea Rufo <www.andrearufo.it>
* @version 20210122
* @link https://www.andrearufo.it/2020/05/05/creare-una-funzione-per-il-tempo-di-lettura-di-un-articolo-di-wordpress/
*/
function get_readingtime(){
// assumed 265 words per minute
$words_per_minute = 265;
// initialize the content
$content = [];
// the article title
$content[] = get_the_title();
// the article content
$content[] = get_the_content();
// all the contents
$content = implode(' ', $content);
// count the words inside the content
$words = str_word_count($content);
// count the seconds for the content
$time = $words / $words_per_minute * 60;
// add the time for 'read' the featured image
if( has_post_thumbnail() ){
$time = $time + 12;
}
// formatting the time
$ii = intdiv($time, 60);
$ss = $time % 60;
$duration = $ii.':'.$ss;
// a most readable format
$timetoread = human_readable_duration($duration);
// Ex. '2 minutes, 52 seconds'
return $timetoread;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment