Last active
December 20, 2016 07:41
-
-
Save gebeer/71dae3821d48fe50d72580f024fdba24 to your computer and use it in GitHub Desktop.
Text Limiter Hook for ProcessWire - adds a new method summarize() to $page - add this code to site/ready.php
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
<? | |
// usage: $page->summaroze($fieldName, $maxLength) | |
$wire->addHook('Page::summarize', function($event) { | |
$fieldName = $event->arguments(0); | |
if(!$fieldName) throw new WireException("No field provided"); | |
// get max length or use 300 as default if none provided | |
$maxLength = (int) $event->arguments(1); | |
if(!$maxLength) $maxLength = 300; | |
$page = $event->object; | |
$value = $page->get($fieldName); | |
if(!strlen($value)) { | |
// requested value is blank, nothing more to do | |
$event->return = ''; | |
return; | |
} | |
// get beginning of value, without any HTML in it (if any) | |
$value = mb_substr(strip_tags($value), 0, $maxLength); | |
// if output formatting on, make sure value is entity encoded | |
if($page->of()) $value = $event->sanitizer->entities1($value); | |
if(strlen($value) >= $maxLength) { | |
// limit length of returned value between words | |
// by truncating to the last space character | |
$value = substr($value, 0, strrpos($value, ' ')); | |
// append an ellipsis to indicate there is more | |
$value .= '…'; | |
} | |
$event->return = $value; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment