WordPress excerpts just the way you want them
Update: I've now written a plugin that does this, so download that rather than editing theme files, if you prefer.
I've spent a lot of time over the last 24 hours trying to change WordPress's the_excerpt() function to play the way I want it to. This is the inbuilt function that (by default) cuts your post's content down to just the first 55 words: it's used extensively in magazine-style themes to give a taster of the whole post.
The problem with the_excerpt() is that it does a whole bunch of stuff you might not want it to. It wraps the shortened content in <p> tags for a start. It's fixed to 55 words, whether those words are wee, or sesquipedalian. And perhaps worst of all, it automatically slaps [...] at the end of the text. Yuck.
There are lots of plugins that deal with this: I first tried Advanced Excerpt, but I couldn't get it to exclude all the tags properly, and ended up with random bits of bold and half-truncated lists in my excerpts. There are lots of solutions posted on this support thread, but when you're attempting to solve all my niggles together, they get messy.
And then it occurred to me: I'm not actually trying to do anything very complicated. I just want to remove the HTML tags, truncate the text (but not be forced to always have all my excerpts the same length), make sure the truncated text doesn't have half a word at the end of it, and finish it off with the ellipsis of my choice. It's so simple, it doesn't need to even be a plugin.
Put this in your theme's functions.php file:
function bm_better_excerpt($length, $ellipsis) {
$text = get_the_content();
$text = strip_tags($text);
$text = substr($text, 0, $length);
$text = substr($text, 0, strripos($text, " "));
$text = $text.$ellipsis;
return $text;
}
then call it from anywhere within the loop like this:
<? echo bm_better_excerpt(600, ' ... '); ?>
where the second parameter is the ellipsis at the end of the excerpt (leave it empty if you don't want anything) and the first is the length of the excerpt in characters: your finished excerpt will probably be a little shorter because the function will trim half-words from the end.
Tags: the_excerpt, WordPress
Posted by Sue on April 4, 2009 in WordPress.








Hi
Of all the solutions for stripping the_excerpt I like yours best, but, I have a problem with posts with attachments, for some reason strip_tags() doesn't strip a part of the tags and I get this text (for example) instead of the excerpt:
[caption id="attachment_1083" align="alignright" width="240"
Any ideas why that should happen?
Thanks
Tom.
Hi Tom,
Thanks for the comment. The reason strip_tags doesn't work is that it only removes HTML tags, not WP's "pseudo-tags" like the caption one. So you'll need to add an extra line of code, just before the strip_tags one. Try this:
$text = preg_replace('`\[[^\]]*\]`','',$text);That will remove everything in square brackets - if you need something a bit more subtle, gimme a shout.