How to use wp_trim_words() to limit words in WordPress

WordPress comes with a built-in function called wp_trim_words(). This functions allows us to limit the text to a specified number of words. You can add this function within your loop to trim the number of words displayed in the_title(), the_excert(), the_content() or anything else you pass to this function.

You may want to use this to make sure that text within title or content doesn’t overflow and break your theme.

$text (string) (required) Text to trim
Default Value: None

$num_words (integer) (optional) Number of words
Default Value: 55

$more (string) (optional) What to append if $text needs to be trimmed.
Default Value: ‘…’


$trimmed = wp_trim_words( $text, $num_words = 55, $more = null );


$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 40, '<a href="'. get_permalink() .'"> ...Read More</a>' );
echo $trimmed_content;

See Also: How to use Shortcodes in your WordPress Themes


Leave a Comment.