0

I'd like to have the first paragraph/sentence of my posts in their single.php page styled differently - say... bold.

How do I go about doing that in the most efficient way?

2
  • Explain why :first-line is not an option. – fuxia Jun 28 '12 at 19:35
  • two reasons: 1. didn't know it exist. 2. I need the first sentence. this only gets me a fragment of it. – Tsahi Levent-Levi Jun 30 '12 at 11:22
1

Here is the idea

add_filter('the_content', 'testfunc');

function custom_formatter($matches){
  return "<strong>{$matches[0]}</strong>";
}

function testfunc($content)
{
  $pattern = "$\<p.*\>(.*)\<\/p\>$";
  $content = preg_replace_callback($pattern, 'custom_formatter', $content);
  return $content;
}

However, you will need a better regular expression in $pattern variable as this regex may be very poor. in the custom_formatter function you can do the formattings you want.

1
  • The above doesn't work. The pattern doesn't really catch the first paragraph. I worked something else out and posted it as an answer here. – Tsahi Levent-Levi Jul 12 '12 at 18:51
0

In the end, this is the function that worked for me:

add_filter('the_content', 'first_line_bold');
function first_line_bold($content)
{
    if (!is_page()) {
      $pattern = "/<p.*?>([^`]*?)<\/p>/";
      $match = "<span style=\"font-weight:bold;font-size:16px;\">$1</span>";
      $content = preg_replace($pattern, $match, $content, 1);
      return $content;
    }
}

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.