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.

7 Replies to “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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: