Are you looking for a way to use wp_trim_words to trim your text in WordPress? While there’s probably a plugin for this, we have created a quick code snippet that allows you to use wp_trim_words to trim your text in WordPress.
WordPress 3.3+ has a core function called
wp_trim_words(). This function will trim text to a specified number of words and return the result. Adding this snippet to your WordPress loop will let you easily trim the number of words displayed within
the_title or any other value you pass to this core function.
All you have to do is add this code to your theme’s single.php file:
echo wp_trim_words( get_the_content(), 100 ); // post content echo wp_trim_words( get_the_excerpt(), 100 ); // post excerpt echo wp_trim_words( get_the_title(), 100 ); // post title
$trimmed = wp_trim_words( $text, $num_words = 55, $more = null );
- (string) (required) Text to trim
- Default: None
- (integer) (optional) Number of words
- Default: 55
- (string) (optional) What to append if $text needs to be trimmed.
- Default: ‘…‘
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 24 best WordPress education themes and how to create a guest post submission form in WordPress.