Add Class to All Excerpts in WordPress

In WordPress, the post excerpt can be displayed using a function called the_excerpt(). This function has no parameters but it does have some filters which you can hook into. I discussed changing the length and the trailing elipses using filters in my article Quick & Easy Excerpt Mods Coming in WordPress 2.9.
Recently, a design I was working on required the excerpts to be styled a certain way. By default, WordPress displays excerpts wrapped in a basic paragraph tag. Without a class or an ID, I had no way of differentiating the excerpt from any other element. To accomplish this I needed to write a function that would hook into the filter the_excerpt and include a class in the paragraph tag.
All it took was a few lines of PHP added to the theme’s functions.php file:

add_filter( "the_excerpt", "add_class_to_excerpt" );
function add_class_to_excerpt( $excerpt ) {
    return str_replace('

With the above code, all excerpts would be surrounded by a paragraph tag with the class "excerpt" which could now be styled using CSS like so:

.excerpt {
  font-size: 14px;
  line-height: 20px;
  background: #eee;
  padding: 10px;
  border: 1px solid #e2e2e2;
  text-shadow: 1px 1px 0 #fff;
  color: #444;
  }

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie