I’ve seen a variety of posts from people devising different ways to customize the_excerpt length. In WordPress, most people are familiar with 2 ways to display their content: the_content, and the_excerpt. Both give fairly predictable results as to what you get. the_content gives you all of your content, with formatting intact. the_excerpt gives you your set excerpt, stripping away formatting, links, etc. But you had one excerpt length, and that was it! What if you want various excerpts? Well I’ve seen ways to craft various excerpts by creating different functions that had to be called per template, but as of WP 3.3 that is no more! Check it out!
First up, credit where credit is due, the inspiration for this post came from c.bavota, and it would be great if you headed over and checked out that article for the lowdown! We’re going to look at wp_trim_words, which I’d played with working on my new theme, but never gotten around to writing about.
With wp_trim_words you can establish what the content is, how many words you want, and what should be displayed in place on the truncated text. It’s simple really. The cool thing here is that on each archive style template, you could display different excerpt lengths. Usage is like this:
<?php wp_trim_words( $text, $num_words = 55, $more = null ); ?>
So we have 3 possible parameters. The first is our content, the second is the length, and the third is the the replacement text. So the example that c.bavota gives is perfect here.
<?php wp_trim_words( get_the_content(), 100, 'Read more $raquo;' ); ?>
Which in our loop would grab the_content, shorten it to 100 words, and add Read More >> to the end of it. SImple right? Instead of creating various functions to make various excerpt lengths, we just adjust our output per template. Since we are working on the_content directly, we shorten the_content. This means that the links, etc. normally stripped by the_excerpt remian intact – definitely something to keep in mind as you may not want that!
Definitely a cool function to keep in mind. If you want true excerpt features (stripping links, formatting, etc.) stick with the_excerpt – but this gives a variety of options to play with. I personally have not fully tested this and would love some further input. This counts words, and truncates. If that truncation happens in the middle of a link let’s say… does your link remain safe, or get cut off halfway? I’m no expert, so I’m not sure how WP handles such things.
For you theme developers out there, I’d love to hear about your successes, and failures, with wp_trim_words! So you have other creative uses for this? I’d love to hear about them too!