Quick tip: Use wp_trim_words() to limit words in WordPress

WordPress 3.3 brought a handy little function with it in wp_trim_words(). An example use case is a height limited box like the one pictured, where you want to make sure that the title and excerpt don’t cause the text to overflow the box.

Using wp_trim_words() allows us to limit the title and excerpt, and anything else really, to a particular number of words. How practical a name. You can define the number of words to limit them to, and also define what you’d like the “more” text to be. My example just uses ellipses.

Below is a gist to show it in use. Everything but the use of wp_trim_words() is totally arbitrary, but there for fun.

Now quit reading and go make some stuff.

20 thoughts on “Quick tip: Use wp_trim_words() to limit words in WordPress

    1. hmm…

      The function is expecting a value for the text that doesn’t return. That’s why you’d use get_the_excerpt() or get_the_title(). It’s your best bet to use functions that do not return and build your own HTML around the results of wp_trim_words() in a stored variable.

  1. My friend u don’t know who easy you make it….maaaaaaaaN. …..I was really searching for this solution from recent two months… NOw i can use it simply and easyle……Thanks bro………….thanks

  2. Hello there. Love this tip. Please can you help with any way to retain the formatting of the text that is called? It seems that it has to wipe out all formatting which is a pain 🙁

    Any help greatly appreciated!

  3. Hi, any advice on that?

    I am currently pulling in custom fields as follows:

    echo wp_trim_words( get_field(‘field_name’), 1000, ‘ ‘ );

    and wrapping in wp_trim_words. It works fine except that there is no formatting…which is no good.

    Hope you can offer some advice.

    Many thanks. AB

    1. If you see my title above, you can see $shorttitle is saving the output of wp_trim_words(). You can use it just like I do where you use the variable it’s saved to in any html format you like. All in the code up there : )

  4. Nice tip!. Would anyone know if it is possible to trim the text once the first full stop is reached…rather than just a random word after a particular number of words reached?

    1. To my knowledge, you’d need custom PHP for that. But be careful, because you never know when a sentence will have a period like Mr. or Ms. or St. or something like that within the first sentence. Would be a tough thing to search for.

Leave a Reply