Trim Your Text with wp_trim_words() in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 26 comments
When I first started putting out Premium themes for WordPress, I create a custom excerpt function that would trim your post content to a certain number of words. Today, I discovered that WordPress 3.3 actually has a similar core function called wp_trim_words()
.
The function works like so:
<?php wp_trim_words( $text, $num_words = 55, $more = null ); ?>
The parameter break down:
- $text
- (string) (required) Text to trim
Default: None - $num_words
- (integer) (optional) Number of words
Default: 55 - $more
- (string) (optional) What to append if $text needs to be trimmed.
Default: ‘…’
If you wanted to display a trimmed version of your content you could do it like so:
<?php echo wp_trim_words( get_the_content(), 100 ); ?>
Using the above snippet within the WP loop would display your content, trimming it at 100 words and adding the default ‘…’ afterwards.
It’s a great function that allows you to automatically trim certain text elements within your WordPress theme.
26 comments for “Trim Your Text with wp_trim_words() in WordPress”