Last active
December 20, 2021 12:23
-
-
Save millipedia/75fea7f7fbf9946f3d5fbcaec0a000c6 to your computer and use it in GitHub Desktop.
Processwire hook to calculate article reading time
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 | |
/** | |
* | |
* Calculate reading time on page save. | |
* Add this to your ready.php file. | |
* Uses a field called 'article_read_time' to store the value | |
* and the field 'page_content' as the readable content. | |
* You'll need to update those field names if yours are different. | |
* | |
*/ | |
function calculate_reading_time(HookEvent $event) { | |
$page = $event->arguments(0); | |
// If this a post then calculate reading time. | |
// You'll need to update this if your template name | |
// is different. | |
if ($page->template->name == 'post') { | |
$page->setOutputFormatting(false); | |
// strip our tags | |
$options=array( "reduceSpace"=> TRUE ); | |
$article = wire()->sanitizer->textarea($page->page_content, $options); | |
$word_count=str_word_count($article); | |
$reading_time_secs=($word_count / 265) * 60 ; // medium uses 265 wpm; | |
// medium allow 12 secs for the first image and then one sec less | |
// for each subsequent image | |
$image_count=substr_count($page->page_content, '<img'); | |
if($image_count>11){ | |
$image_count=11; | |
} | |
$image_value=12; | |
for($i=1;$i<$image_count;$i++){ | |
$reading_time_secs+= $image_value; | |
$image_value--; | |
} | |
$reading_time_mins=ceil($reading_time_secs/ 60); | |
if($reading_time_mins > 7){ // round up to nearest 5. | |
$reading_time_mins=round(($reading_time_mins + 5 / 2 )/5)*5; | |
} | |
// actually it just looks better as min... | |
// $page->article_read_time = $reading_time_mins . ($reading_time_mins>1 ? ' mins' : ' min'); | |
$page->article_read_time = $reading_time_mins . ' min'; | |
} | |
} | |
wire()->addHookAfter('Pages::saveReady', null, 'calculate_reading_time'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment