wp_trim_words()
Sometimes you need quick solutions for different WP needs. I am sure you have library full of reusable and codex quality snippets. Came across this which came through in a pinch. Do you need to shorten that string of text in your WordPress theme? You’re in luck! wp_trim_words() is an easy-to-use function that will get the job done. All it needs are two arguments – the original string and how many words you want included in its trimmed version, plus there’s even a helpful ellipsis (…) at the end by default. Ready to give it a try yourself?
Check out our example below for guidance:
Trimming the title
[sourcecode language=”php”]echo wp_trim_words( get_the_title(), 5); // for the post title[/sourcecode]
Trimming the content
[sourcecode language=”php”]echo wp_trim_words( get_the_content(), 20); // for the post content[/sourcecode]
Trimming the excerpt
[sourcecode language=”php”]echo wp_trim_words( get_the_excerpt(), 10); // for the post excerpt[/sourcecode]