Home / Design Blog / wp_trim_words: WP Excerpt Alternative

wp_trim_words: WP Excerpt Alternative

By: Simon
Updated:
Jan 5, 2023
Posted: Aug 28, 2014

wp_trim_words()

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]

Simon Urbina

Simon Urbina

Simon is a Product Designer and Front End Dev with over 20 years of experience. He started as a graphic designer and illustrator coding his first website in 1996. He has worked with brands like Publix, Microsoft, and Discovery Channel.