Soliloquy - The Best Responsive WordPress Slider Plugin

Limit Content Length in WordPress with wp_trim_words()

Share This Post

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!

Have you enjoyed reading Limit Content Length in WordPress with wp_trim_words()? Sign up below to get regular content updates and also get my "7 Tips to a Professional WordPress Setup" absolutely free!

About Thomas Griffin

I live and breathe WordPress. I create products around WordPress (Soliloquy and OptinMonster), contribute to WordPress core and do lots of fun development around WordPress in general. You can find me on Twitter, Facebook and Google+.

7 Responses to “Limit Content Length in WordPress with wp_trim_words()”

  1. Jamie Mitchell says:

    Awesome! thanks

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

  2. WP Mayor says:

    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…

  3. webapptester says:

    You saved me! :D

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

  5. Bill Koontz says:

    this worked like a charm.. thanks all!

  6. Its working fine. Thanks.

  7. Sallam says:

    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.

Leave a Reply