WP – Add class name to first paragraph in blog post

When re-designing my blog I wanted to display the first paragraph of each blog post in bold text. A CSS3 selector could have been used, but wouldn’t work in older browsers such as IE6.

Instead I decided to write a very simple function to add a class name to the first paragraph by filtering the content, then setting the styles accordingly in my theme CSS file.

function first_paragraph($content){
	return preg_replace('/<p([^>]+)?>/', '<p$1 class="first">', $content, 1);
}
add_filter('the_content', 'first_paragraph');

By default this will append class=”first” to the first p tag in your post.

If you want to use this function on your own blog, just add it to your (or create a)  functions.php file within your themes folder.

6 thoughts on “WP – Add class name to first paragraph in blog post

  1. Hmmm…

    This is not working for me at all.

    I know the functions.php file is being read as when I took off the <?php bit off of the front, the contents of the file ended up as raw text at the top of the index page of my site.

    Any tips?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>