Making WordPress’ the_excerpt() better

the_excerpt() improvements

Not that long ago I got into WordPress coding in a big way. A lot of small bits to get you started. A large shortcode, playing with the_loop to either send the user to a random post.

What I needed was a way to control the number of words in the_excerpt as well as other bits and pieces.  I was doing this via a plugin, Auto Excerpt everywhere, that duplicated what is on the homepage.

Back to the code, and the point of this post. The code can be added to the theme’s functions.php file or to the theme file that this change is needed. It’s up to you on how you do it.

What I wanted to do is display the_excerpt in a way that was controllable.  After a smidgen of searching I came across Aaron Russell’s excellent post about improving the_excerpt.  That became the basis of the script.

There are two important variables that can be modified to help get your desired output.

The first is line 4. This sets the number of words that will be outputted when the_excerpt() is called. You may want more, or less than the default 55 words.

The second is line 9. using PHP’s strip_tags(). In this case, I have decided not to allow any HTML tags to be used.

Just modify it, like the below, that will allow <p>, bold or italics to be allowed.

It’s better to use older and newer version of tags as some people, like myself, use the older version of <strong> and <em> [ <b> & <i> ] tags.

Improving Search using the_excerpt

It’s nice to see your search term highlighted. This can be done using the same filter. This addition starts at line 14. This simply checks to see if were not on the search display page.

Two things to notice are lines 17 and 21.

Line 17 is a line to mention. Line 21 is just there to remove what has been added. This line makes sure that special characters are handeled correctly and it doen’t break the replace at line 21

Finally, let’s look at the CSS that is mentioned at line 20. This will need to be added to the theme’s style.css file. All it does is add a yellow background to the search term.

Finally, a quick way of changing the_excerpt length.  This can be useful on pages that only a small number of words are needed.  A home page showing a number of “news items” for example.  I use it in some pages where a different style of excerpt is needed.

When I found the code that did both of the things I needed, I also discovered a problem with the code. It won’t work highlighting the_title, if used as a link. I think it needs a reworking of the preg_replace command… That’s for another day or for you to help.