wp_trim_words() is a nifty function added in WordPress 3.3 that allows you to set the character/words limit for a specific block of content.
wp_trim_words() takes 3 params: $text, $num_words and $more.
$text is simply the text you want truncated. wp_trim_words() will take this text and strip out all the tags before truncating it. The cool thing about this function is that it is localized, so translators can specify how they want the text truncated. The text can be truncated based on words or character count, which can be helpful for languages where the word count is based solely upon single characters.
$num_words is an integer that specifies how many words you want to display before the text is truncated. The default setting to this is 55.
$more is the text appended to your truncated content. It is set to … by default, but you could change this into something like a “Read More” type of thing if you want.
Let’s say you want to limit the output of your content to 80 words. We can do a simply query and use wp_trim_words() to achieve this with relative ease.
As you can see from above, we are simply creating a new query and outputting the title and content, only the content is being truncated by wp_trim_words() to only show the first 80 words.
Limiting the content length is now a piece of cake with this nifty little function – hope you can find some uses for it in your upcoming projects!
