Limit Content Length in WordPress with wp_trim_words()

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!

Enjoy? See Inside my WordPress Toolbox

Over 20,000 people have purchased my WordPress products. Get absolutely FREE access to regular updates and my toolbox - a collection of WordPress-related products and resources that every WordPress professional should own.

  • Jamie Mitchell

    Awesome! thanks

    how can i add the read more aswell? it does not seem to show

  • http://twitter.com/wpmayor WP Mayor

    Would be nice if this function would have the option to not strip out all tags, and also to add a read more link. Having “Read More” without it being a link is a bit useless…

  • webapptester

    You saved me! :D

  • http://www.narga.net/ Nguyễn Đình Quân

    I find it! It’s allow me cut-down the post content on the front page :)

  • Bill Koontz

    this worked like a charm.. thanks all!

  • http://www.hostingforest.net/ prakash prakash

    Its working fine. Thanks.

  • Sallam

    Can we use this to limit the max characters of each word in comments? I need to stop people from writing repeated letters like “toooooooooooooooooooo long” and possibly change it to “too long”, allowing a max of 2 consecutive letters in each word.