Skip to content

Instantly share code, notes, and snippets.

@millipedia
Last active December 20, 2021 12:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save millipedia/75fea7f7fbf9946f3d5fbcaec0a000c6 to your computer and use it in GitHub Desktop.
Save millipedia/75fea7f7fbf9946f3d5fbcaec0a000c6 to your computer and use it in GitHub Desktop.
Processwire hook to calculate article reading time
<?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