Limit the_excerpt with max of x characters

add_filter('wp_trim_excerpt', function($text){    
   $max_length = 140;

   if(mb_strlen($text, 'UTF-8') > $max_length){
     $split_pos = mb_strpos(wordwrap($text, $max_length), "\n", 0, 'UTF-8');
     $text = mb_substr($text, 0, $split_pos, 'UTF-8');
   }

   return $text;
});

This should take into account your max length and split the text at the nearest word boundary.
Apply the filter, and call the_excerpt(); in your templates


Apparently there’s a wp_trim_words function from WP 3.3 that you can also use, but from the source looks very inefficient. Appart from using 3 regexes, it splits the text into an array of words, and this can get very slow and memory exhaustive for large chunks of text…

Leave a Comment