Limit the excerpt to a number of characters, instead of words

Hello Developers, I am going to show you how to limit the excerpt to a number of characters, instead of words without cut off in mid-sentence.

If you are in trouble about cut off the characters in paragraph using excerpt code. Just like my below screenshot.

Then don’t worry I have short and simple solution for it

The first thing to do is Open your functions.php file and paste the code below in it.

function custom_short_excerpt($excerpt){
$limit = 15; // you can add set the limit for character here which you want to show the character in paragraph
if (strlen($excerpt) > $limit) {
return substr($excerpt, 0, strpos($excerpt, ' ', $limit));
}
return $excerpt;
}
add_filter('the_excerpt', 'custom_short_excerpt');

And the result is here:

The benefit of this code is if you set 15 character limit for any string; for example the string is “Lorem ipsum is simply”.

Then last words (simply) will be cut to (sim).

If you use above code then words will not cut but whole word will be hide from whole string so result will be “Lorem ipsum is” only.

Which seems meaningful.

Thank You 🙂

Blog Catagory : WORDPRESS