Automatically Highlight First Paragraph of Post Content

How to Automatically Highlight First Paragraph of Post Content

in Posts & pages
Google+ LinkedIn

You might have noticed this on some websites that they highlight first paragraph of the article slightly different than the rest of the content. Some website use larger font size for first paragraph, some make it bolder than the subsequent paragraphs and some change the color style of the text. It looks nice and cool, isn’t it? So in this article I will show you how to highlight first paragraph of post content and style it differently. We can also achieve this by using CSS :first-child pseudo class selector but this won’t work uniformly across all the browsers such as older version of Internet Explorer and besides, where is the fun in that.

To highlight first paragraph and make this work across all browsers, we will be adding a CSS class to the first paragraph of our post content, with the help of WordPress filter. After adding a class on first paragraph, it’s up to us how do we want to style it. Well, I will also write couple of different CSS rules to highlight first paragraph text. So are you ready to be highlighted?

In order to add a class to the first paragraph of the post content in the WordPress loop, simply place the following code snippet into your themes function.php file. This will automatically append class=”highlight” to the first p tag in your post.

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

Now we can define some CSS rules to highlight first paragraph. You can use following CSS code to use bold text for first paragraph.

/* bold text in first paragraph */
p.highlight {
    font-weight: bold;
}

Or use this one to increase font size.

/* larger font size for first paragraph */
p.highlight {
    font-size: 1.4em;
}

Share the love

If you like this snippet, share it with others!

Leave a Reply

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