Let's say I want to give the first paragraph bold text by adding a body class to the first paragraph. Is there a way to filter the output of


or any other paragraph? First paragraph? Last paragraph?

I know I can do this using Javascript or CSS (:firstchild), but is there a native WordPress way?




The following bit of code adds a class to the first paragraph output by the_content:

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

Add the above to your theme's functions.php file.

Then in your CSS add something like:

p.intro { font-weight:bold; }

I can't claim credit for this solution (see this thread in the WP forums) but I tested it and it worked great for me in WordPress 3.3.2. You should be able to modify it as needed to target whichever paragraph your heart desires.

  • 2
    There is an issue with this: If there is already a class assigned, you will end up with two class attributes. – mor7ifer May 9 '12 at 23:26
  • 1
    @m0r7if3r Plus: It won't work for anything than the 1st paragraph – kaiser May 10 '12 at 0:21
  • @m0r7if3r, can you help me understand when that would be an issue? – Ryan May 11 '12 at 18:28
  • @Ryan Absolutely. If the first <p> of the_content looks like <p class="any_class more_classes">, it will be automatically replaced with <p class="intro"> rather than becoming something like <p class="any_class more_classes intro'>. As I consider it now, I believe it might be possible to design a regex that would do the classname extraction for you... – mor7ifer May 12 '12 at 2:55
  • @Ryan Absolutely, Thanks! It worked. This option enables us to call a specific part of the_content(), right? Do you know how to call the first paragraph into a the_content() function? – user16074 May 13 '12 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.