Often when people truncate text in their WordPress excerpts or sample text, they simply limit the total number of characters and add an ellipsis. It’s pretty easy to do, but it usually ends up with a word being broken at the end.
For exampl…
This function will truncate any phrase by the number of words you specify and add an ellipsis if you specify one.
function ssm_truncate($phrase, $max_words, $ellipsis = '') { $phrase_array = explode(' ',$phrase); if(count($phrase_array) > $max_words && $max_words > 0) $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).$ellipsis; return $phrase; }
One could expand on this and also add a character limit in the event that the phrase contains several long words. Perhaps I’ll do that someday.