Last active
January 21, 2021 23:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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