wp_trim_words

Home » Functions » wp_trim_words

Function Name: wp_trim_words

Are you tired of long blocks of text on your WordPress website? Fear not, because the wp_trim_words function is here to help!

The wp_trim_words function is a handy tool for trimming text down to a specified number of words. It’s commonly used in WordPress themes to display excerpts or summaries of blog posts.

Here’s how it works: you pass the function a string of text and a desired word count, and it returns a shortened version of the text that contains only the specified number of words. It also adds a suffix, which by default is an ellipsis (…), to indicate that the text has been truncated.

Here’s the function signature:

wp_trim_words( string $text, int $num_words = 55, string $more = null )

As you can see, the function takes three parameters:

  • $text is the string of text you want to trim.
  • $num_words is the number of words you want to keep. By default, it’s set to 55.
  • $more is the suffix you want to append to the end of the truncated text. If you don’t specify a value for this parameter, the default ellipsis (…) will be used.

Here’s an example of how to use wp_trim_words:

$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.";

$short_text = wp_trim_words( $long_text, 10 );

echo $short_text;

In this example, we’re passing a long block of text to the wp_trim_words function and telling it to keep only 10 words. The function returns a shortened version of the text with an ellipsis (…) at the end, which we then echo out to the screen.

And that’s all there is to it! With the wp_trim_words function, you can easily trim down long blocks of text and keep your website looking clean and organized.

Learn More on WordPress.org

WordPress snippets using the wp_trim_words function

Register an account to save your snippets or go Pro to get more features.