Skip to content

Instantly share code, notes, and snippets.

@ryangittings
Created May 13, 2019 10:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryangittings/4308d3bbde62537186adda25300106c4 to your computer and use it in GitHub Desktop.
Save ryangittings/4308d3bbde62537186adda25300106c4 to your computer and use it in GitHub Desktop.
Perch template filter for getting a Perch item's reading length in minutes
<?php
class PerchTemplateFilter_length extends PerchTemplateFilter
{
public function filterBeforeProcessing($value, $valueIsMarkup = false)
{
$word = str_word_count(strip_tags($value));
$m = floor($word / 200);
$s = floor($word % 200 / (200 / 60));
if ($m > 0) {
$est = $m . ' minute' . ($m == 1 ? '' : 's');
} else {
$est = 1 . ' minute';
}
return $est;
}
}
PerchSystem::register_template_filter('length', 'PerchTemplateFilter_length');
@ryangittings
Copy link
Author

Usage example:

<perch:blog id="postDescHTML" filter="length">

@muster-mark
Copy link

Looks like you intended to use $s before the 's', but didn't.

@ryangittings
Copy link
Author

ryangittings commented Oct 16, 2019

Which 's'? The s on line 12 is to append to the word 'minute' if there are multiple minutes :)

But you're right, the $s variable is there if you did want to use seconds. It's here for demo purposes!

@muster-mark
Copy link

Ah right, I thought the 's' was for seconds, but I see what is happening now :)

@jsphpndr
Copy link

This only seems to work for the "postDescHTML". Is there a way to include block tags to the total count?

@ryangittings
Copy link
Author

I'm not sure if this is possible, it's mainly for text fieldtypes. If I have some time I'll take a peek!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment