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.
Well done you – not just pretty hair…
LikeLike
Thank you so much! That’s exactly what I was looking for! Works great.
LikeLike
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?
LikeLike
My mistake! It was a conflict with a plugin that was preventing the function from formatting the post.
Thanks!
LikeLike
Really thanks for this tip.
LikeLike
cool!
regular expressions are something that i still struggle with…
LikeLike
This is perfect thank you for sharing this bit of code. I was Googling for a few mins, I figured it was nothing too complicated.
LikeLike