Brilliant little snippet from Benjamin Reid http://www.nouveller.com/quick-tips/quick-tip-8-limit-the-length-of-the_excerpt-in-wordpress/
In his words…
Right here’s the scenario. On one of your clients post page’s you use the_excerpt
function to display an excerpt for each post. You’ve got room for a decent size excerpt and explain to them they can put about a paragraph into each excerpt, 100 words or so.
They then ask for a mini news feed that they want to appear on the homepage. You go ahead and add it and all of a sudden you’ve got paragraphs of text cluttering up the home page. You can either now go and tell them they can only use 10 words in each excerpt (which will look ridiculous on the posts page) or explain to them how to create a custom field which is an excerpt of the excerpt… or…
Rather than confuse them we’re just going to create a really simple way to limit the amount of words when displaying the_excerpt
, we’re not limiting the word count from the posts edit screen remember. Just the small excerpt that we want to appear in mini news feed on the home page, only about 10 words.
Open up functions.php
Let’s start by writing our function that will shorten the_excerpt
. Open up functions.php
from your theme folder and add this function in. The explanation is commented for you.
function limit_words($string, $word_limit) { // creates an array of words from $string (this will be our excerpt) // explode divides the excerpt up by using a space character $words = explode(' ', $string); // this next bit chops the $words array and sticks it back together // starting at the first word '0' and ending at the $word_limit // the $word_limit which is passed in the function will be the number // of words we want to use // implode glues the chopped up array back together using a space character return implode(' ', array_slice($words, 0, $word_limit)); }
Go to your loop where you’re using the_excerpt
I’m doing this in the mini news feed loop. So find:
<?php the_excerpt(); ?>
And replace it with this:
<?php echo limit_words(get_the_excerpt(), '10'); ?>
First we echo
our function (as it returns
a value), we then pass the string through that we want to chop. You have to use get_the_excerpt
as this returns
the excerpt rather than echo’ing it like the_excerpt
does. Finally we pass the number of words we want, in this case 10.
Voila! Easy right?