Tag cloud
See my latest projects
About this site
This site is proudly powered by WordPress. If you like what you see, why not subscribe?
Copyright © 2008-2010 Aaron Russell. All rights reserved.
Thursday, 13 November 2008

Are you having trouble with your excerpts? Is WordPress misbehaving and making your theme look downright shoddy when all you want to do is use it’s native excerpt function? You’re not alone so read on.
Wordpress’ the_excerpt() template tag is used in most themes for browsing the archives and categories of a blog. Rather than displaying the full content of the post, the excerpt displays a short snippet of the content. Unless you manually enter in an excerpt when writing each post, WordPress grabs the first 55 words of the post and uses that as the excerpt.
So far so good, but there are problems with the way WordPress does this. These include:
There are ways to fix these problems, and I will show you how. Better yet, these changes can be done completely within your theme without having to hack away at the WordPress core files.
The first thing we need to do is find the relevant excerpt function that is not doing its job very well. Actually, you don’t need to find it because I’ve done it for you, but if you insist you can find the code below deep within wp-includes/formatting.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function wp_trim_excerpt($text) { // Fakes an excerpt if needed global $post; if ( '' == $text ) { $text = get_the_content(''); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]>', $text); $text = strip_tags($text); $excerpt_length = 55; $words = explode(' ', $text, $excerpt_length + 1); if (count($words)> $excerpt_length) { array_pop($words); array_push($words, '[...]'); $text = implode(' ', $words); } } return $text; } |
Remember, we are not altering the core files here, so we need to copy this code and paste it into our theme files. Open up your functions.php theme file and paste the code in.
This function is called wp_trim_excerpt() but it is important that we call it something unique. I’m going to rename it improved_trim_excerpt() but you can call it what you want. Edit line one accordingly:
1 | function improved_trim_excerpt($text) { |
This is simple. Find line eight and change the value to whatever you want – lets say 80.
8 | $excerpt_length = 80; |
If you have problems with your formatting you may need to include the P tag. You may want to include links or even images. Find line seven and replace it with this:
7 | $text = strip_tags($text, '<p>'); |
You can simply list as many tags as you need to immediately following the P tag.
To remove unwanted script code you need to add another line. In-between lines five and six add the following:
6 | $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text); |
OK, that’s sorted out all our problems. Just to clarify your new and improved function should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function improved_trim_excerpt($text) { global $post; if ( '' == $text ) { $text = get_the_content(''); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]>', $text); $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text); $text = strip_tags($text, '<p>'); $excerpt_length = 80; $words = explode(' ', $text, $excerpt_length + 1); if (count($words)> $excerpt_length) { array_pop($words); array_push($words, '[...]'); $text = implode(' ', $words); } } return $text; } |
The final thing we need to do is tell WordPress to use our new and improved function rather than its built in function. Fortunately this is a piece of cake and involves entering two more lines at the end of our functions.php theme file.
20 21 | remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'improved_trim_excerpt'); |
That’s everything complete. You’re now set for improved excerpts.
Thats nice, I am gonna use this code in a widget plugin I am developing.
Hi
This is brilliant, clearly explained and really works well. Thanks!
Only problem is, it doesn’t end the tags , unless the ‘ ‘ is included in the excerpt length, so you run the risk of, say, the rest of your page after a long ‘< em>‘ excerpt turning out italicised.
Including the end tags in the list in the theme functions.php file doesn’t work.
To get around this, I put a end tag for each of the tags I included after ” in my theme archive.php file. It runs the risk of orphaned stop tags, but that’s better than everything being italicised or bold.
If you can think of a more elegant solution, I’d be grateful.
Also, just a note for clarity for php novices like myself: when listing the tags in the theme functions.php file, Don’t list them like this:
‘ ” ‘< em>‘ ‘< strong>‘ ‘
List them like this:
‘ ‘ < em> < strong>‘ ‘
Hi
Oops, all the html was read in my post – if you think it’s useful, could you mend it, please? I can’t get in and edit it…
Thanks for the post, this is exactly what I needed (and the 3rd result on Google for “the_excerpt” : ) . One other thing I’d like to figure out is how to make this ” [...] ” into something like this ” read more… ” with a Permalink to the post. Can that be achieved via this method also?
Cheers!
Hello, Great piece of code here. I am having trouble getting it to work though. I understand what is going on and everything, but when I use “the_excerpt” to call on the post body, I am still getting all the data. It wont cut off with my read more link.
I followed the directions perfectly, added the function into my theme functions.php file, but for some reason Im still not getting it to show up. Email me at rlkennedy85@gmail.com if you think you can help. It would be greatly appreciated. Thanks again for the great code.
This seems to cause a headers error with WP 2.7.
Warning: Cannot modify header information – headers already sent by (output started at /////blah////functions.php:12) in /////blah/////functions.php on line 698
Warning: Cannot modify header information – headers already sent by (output started at //////blah/////functions.php:12) in /////blah/////functions.php on line 699
In this case, I was adding a new post.
This probably because the wp_trim_excerpt function in 2.7 seems to be written differently?
having trouble with this in 2.7 too when i choose “update post” it gives a similar header error- any ideas?
If you just want to strip tags, try something like this,
<?php echo strip_tags(get_the_excerpt(), ‘<big><small><em><i>’); ?>
@Steve & @david – Thanks for informing me this hack is broken in WP 2.7. I’ll update the post accordingly and look to see if the instructions can or need to be updated.
@JHB – Yep, that works too. Thanks for the input.
Looking forward to this fix.. i was scratching my head when I receive those errors. DAMN WordPress!!!! Why does it break at least one plugin when it updates???
I’ve just edited my first core wordpress file to get the_category doing what I want. And then, likewise, WP2.7 comes along and all the instructions go wrong. Sigh.
Much cleaner than hacking the core files, and useful way of stripping out scripts – thanks for a neat summary!
[...] Russell ha hecho su propia función para generar excerpts con etiquetas HTML, que además permite elegir el número de caracteres que [...]
Thank you! Your post helped me a lot to get better control over WP’s default ” [...] ” displayed from the_excerpt … It’s great you can control things like this through a theme and leave core files alone
Brilliant How to – Should be made core.
Greetings,
Good work and it’s going well with me but one thing i cant sort out, the formatting is still without any styles like font color and size also no list…etc.
i cant see an option where to activate those seems it’s by default strips the formatting.
i need this function to only strip img tag
thanks
Thanks, Aaron, for this great function.
Just a little additional information for you and your readers; If you are having trouble with unclosed tags (like julia, above), after this line (at the end of the function):
$text = implode(‘ ‘, $words);
add this line:
$text = force_balance_tags( $text );
That should balance any open tags automatically. Works perfectly on my setup, and I hope it will help for others.
Wow, great “hack”, I use the_excerpt a lot in my templates. I wonder though, is there a way to trigger the_permalink inside the [...] to link to the full post? Thanks again, nice job!
why we can’t ad the_excerpt (‘xxx); ?
xxx=length.
This was incredibly helpful and easy to follow.
The only thing I got stuck on was realizing that $excerpt_length refers to 80 WORDS, not 80 CHARACTERS. All’s well now.
Thank you!!
FINALLY!!! I’ve been looking everywhere for a clean and quick hack for my excerpts. Thanks so much!
One question: Is it possible to add styles to the images in excerpts? My images are displaying right next to the test and I would like to add a margin.
Thanks again!
Duh – styles are part of the theme, not functions. Ignore my last comment. Thanks!
Thank-you Thank-you Thank-you! Very valuable post and easy to follow. Added to the $text = strip_tags($text, ”); and now the links work our main page.
thank you so much for this posting!
quick question…. how is it possible to replace the ‘[....]‘ with the URL of the post?
i was trying to replace this: ‘array_push($words, ‘[...]‘);’
with this:
‘array_push($words, ‘[<a href="" title="">]‘);’
but this gave an error ![]()
i guess that just because i am a novice to php?
can someone help me get this right?
Thanks again!!!!
Thank you, this was exceptionally clear and helpful, and works like a charm. The excerpt issue was driving me nuts and I couldn’t figure out how to change it. Thanks so much for sharing your knowledge and effort with everyone else!
[...] Improving WordPress’ the_excerpt() template tag [...]
Where does the [code]remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');[/code] go in the functions.php file?
Inside of the php end tag, I assume. But where? Thanks!
[...] Source: Aaron Russell – Improving WordPress’ the_excerpt() template tag [...]
This is an extremely helpful tip, Aaron. Thank you very much.
Do you have any advice if we are actually trying to keep Javascript within our excerpts?
For example, I’m using the ProPlayer plugin to display a Flash mp3 player and it works great when displaying the entire contents of the post. However, if an excerpt of the post is displayed, the Javascript used to display the Flash player appears instead of the Flash player itself.
http://aflourishinglife.com/category/audio/
Thank you for any assistance you can offer.
Adam
Thanks for sharing this code! wasnt a big fan of actually messing around with the core WP files but this seems easier, will give it a shot! thanks
how can I make the length a variable? I want to pass a length value if I don’t want to use the default length.
for example:
improved_trim_excerpt($text,$w) {
$excerpt_length = $w;
}
Please advice.
Thanks,
Marvin
Fantastic article. Thanks. I actually got an email from a cutomer who noticed that her links didn’t work everywhere that the excerpt was used. I was able to use your tutorial to fix the problem. It took me less than 20 min to find you and fix the issue. So..Thanks!
Hey everyone, thanks for your comments and sorry for taking my time in getting back to some of you personally.
@Raphael – Someone’s asked me that before but I’m afraid I don’t know the answer to that one. I’m sure what you’re trying to do IS possible, but I’m afraid it’s not going to be as simply as chucking a < A > tag into the function. Let me know if you suss it out.
@Adam – Hmmm, you *could* remove the preg_replace line (line 7) and then add the < SCRIPT > tag to the strip_tags statement on line 8… but I’d advise against it. The function will split your content after 80 words which will include any javascript, which means it could split right down the middle of your script. That would leave a pretty horrible mess!
@marvin – Again, not sure I can help with that one. I think you’d have to modify core files in order to do that. Probably best not to.
@everyone else – cheers for all the cool comments
This is an excellent plugin! I did notice an error using this in conjunction with the NextGEN plugin … specifically the “slideshow” feature, which utilize short code for Flash implementation.
It is easily fixed by adding this line in after the “get_the_content” function (second line in the if() statment:
$text = strip_shortcodes($text);
Thanks again!
Thanks for this Aaron — really useful.
the_excerpt () has always been a problematic feature of WP, and I hope you will contribute your ideas here to the WP traclist, because it much improves the use of the tag.
What would be really nice is if the excerpt functioned better, with more parameters for templates, and even better would be if the built-in admin panels allowed you to configure the default behavior without editing code (e.g. specify what should be filtered out, the length, the read more link, etc.)
And the full editing box should be available for excerpts, as well as the ability to create excerpts for pages without the use of plugins. (Come on, WP, a page is just a type of post, it’s a no brainer to add the excerpt box for pages.)
Anyway, thanks — people like you are why I keep sticking with WP!
It’s such a widely used tag, but still lagging in useful functionality.
By the way, others may find this bit of code for the excerpt useful (taken from Ian Stewart’s Thematic Forums at http://themeshaper.com/forums/ and supplied by Chris — can’t find exact link right now):
// This function filters out the default ellipses [...] and replaces them with a more link
function excerpt_ellipse($text) {
return str_replace('[...]', '
[...More »]', $text);
}
add_filter('get_the_excerpt', 'excerpt_ellipse');
It could be incorporated into your function, I believe.
@marvin – instead of editing the function prototype, you could get the value from a constant or an option somewhere in the WP Admin.
So you could make it either:
define(‘EXCERPT_LENGTH’, 25);
improved_trim_excerpt($text) {
$excerpt_length = EXCERPT_LENGTH;
}
or
improved_trim_excerpt($text) {
$excerpt_length = get_option(‘excerpt_length’);
}
(of course you’ll have to add the option first – would be worth creating a plugin to do this, as it’d separate it out. In fact, this might be my next blog post…)
[...] [...]
Thanks a lot for the clear and easy steps. It saved my time with removing JavaScript “var fbShare = {url: …..” from my site…
For those looking to add an anchor tag to the [...] tag, change your “if” statement to the following.
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, ‘[...]‘);
$text = implode(‘ ‘, $words);
echo “read more“;
}
It works for me, except for the fact that I can’t get the “read more” to appear at the end of the excerpt. :-s
[...] best solution we have found to these limitations was provided by Aaron Russell, but this also had just a couple of stumbling blocks, as evidenced by reading through the comments [...]
I have come up with a working solution to the problem of adding a “read more” link (or some sort of anchor tag) to the ‘[...]‘ at the end of the excerpt. I have also included my ‘balanced tags’ solution from above.
I would post it here, but the filters would eat the code, so I posted a short article at my site:
Fixing The Excerpt In WordPress
If you would like, you can change the ‘[...]‘ to ‘read more’ or whatever you would like it to say. I hope you all can stop by and check it out.
Aaron, take a look at this ticket http://core.trac.wordpress.org/ticket/10395. It fixes some of the problems described here by introducing extra filters (number of words and the excerpt ending) but it still forces tag stripping.
Just thought I’d let you know.
Great tip, i was in the need for this. Thanks!
Excellent, this is exactly what I was looking for! Many thanks for the easy to follow post!
I might just mention that the code in the post is extremely difficult to read… Dark blue text on a dark grey background is not an ideal combination!
Last week I asked the question on Twitter, “What HTML element do you use for each line of a form? P, DIV, or something else?” So, how do you do your forms?
This years season of 24 ways article has come to a close and with it a reoccurring theme of controversy has arisen: designing in the browser. I offer my thoughts on why it misses the point.
The problem with CSS pre-processing frameworks is that they don’t really fit within the average web designers’ work flow. So I built an extension to LESS for creating cached stylesheets your PHP projects can use.
Are you a web designer or are you a web developer? Let me guess, you are a bit of both. Does that mean you are “doing it wrong”?
If you’re like me then your life revolves around email. Unfortunately the grip that email now has on all our lives creates as many problems as it solves. Learn how I control my Inbox.
“@JohnONolan have you got me mixed up with some other @aaronrussell or have I been sleep-tweeting again?”
Posted about 2 hours ago.
This site is proudly powered by WordPress. If you like what you see, why not subscribe?
Copyright © 2008-2010 Aaron Russell. All rights reserved.