PHP Function to limit content with complete word

The following function can be used to limit the content with a complete word rather than broken words.

function casper_content_limiter( $text, $length = 64, $tail="" ) {
	$text =	trim($text);
	$txtl =	strlen($text);
	if( $txtl > $length ) {
		for( $i = 1; $text[$length-$i] != " "; $i++ ) {
			if( $i == $length ) {
				return substr( $text, 0, $length ) . $tail;
			}
		}
		$text =	substr( $text, 0, $length-$i+1 ) . $tail;
	}
	return $text;
}

In wordPress paste the above function in the function.php file in the theme folder. After that call the function from the template file or any other file where you want to limit the content by

$limited_content = casper_content_limiter( $content, 80, '...' );

Now $limited_content contains limited content.
In the function, first parameter, ‘$content’ is the actual content which wants to be limited.
Second parameter is the limit count. ie characters to be limited.
Third parameter is the string/character to be appended at the end of the limited text. here it is ‘…’.

Related Posts

Leave a Comment

DON’T MISS OUR GIVEAWAYS!
Subscribe To Newsletter
Subscribe to our newsletter and get all the latest updates offers and giveaways right in your inbox.
Subscribe
Give it a try, you can unsubscribe anytime.
close-link

Join Free Giveaway!

Subscribe to our newsletter to get latest offers and giveaways!
SUBSCRIBE
close-link