Thursday, 13 November 2008

Improving WordPress’ the_excerpt() template tag

JavaScript code

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:

  • Word count - 55 words is a good number, but what if you want more or less?
  • Formatting - WordPress strips out all HTML tags. This gets rid of images and links, but can also get rid of paragraph formatting, making the entire excerpt one long paragraph without any line breaks.
  • JavaScript - Unfortunately JavaScript isn’t stripped out, which can result in some plugins’ messy script appearing in your excepts. Not only does this look rubbish, it can be a vulnerability too.

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.

Finding the excerpt function

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) {

Increase the word length of the excerpt

This is simple. Find line eight and change the value to whatever you want - lets say 80.

8
$excerpt_length = 80;

Include HTML tags

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.

Remove unwanted JavaScript code

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(']]>', ']]&gt;', $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.

This article was originally published on miLienzo.com on 2 September 2007.

7 fantastic comments

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?

What are your thoughts?