Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have some code that uses preg_match to grab the first paragraph, and then spit it out in the loop:

function first_paragraph() {
  global $post, $posts;
  $first_para = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('%(<p[^>]*>.*?</p>)%i', $post->post_content, $matches);
  $first_para = $matches [1] [0];
  echo $first_para;
}

However, there is a little problem with this. It only works when I manually wrap text in <p> </p> tags in the editor, and not otherwise. Regular expressions are certainly not my forté, so any help or further understanding would be great.

And this works, also wraps the images/iframes in p tags:

function first_paragraph() {
  global $post, $posts;
  $first_para = '';
  ob_start();
  ob_end_clean();
  $post_content = $post->post_content;
  $post_content = apply_filters('the_content', $post_content);
  $output = preg_match_all('%(<p[^>]*>.*?</p>)%i', $post_content, $matches);
  $first_para = $matches [1] [0];
  echo $first_para;
}
share|improve this question
add comment

1 Answer

Try this:

function first_paragraph() {
    global $post, $posts;
    $post_content = $post->post_content;
    $post_content = apply_filters('the_content', $post_content);
    $post_content = str_replace('</p>', '', $post_content);
    $paras = explode('<p>', $post_content);
    array_shift($paras);

    return $paras[0]; 
}
share|improve this answer
    
Nope! That doesn't produce anything, even when I manually add <p> in the editor. Is it something to do with post_content not formating like the_content()? –  tmyie Dec 20 '13 at 12:06
    
WordPress will automatically add <p> tags to your content, that is what apply_filters('the_content'); does and wpautop, strange that this does not work as I grabbed this from a site I worked on recently but It grabbed the first two paragraphs so I could stick them in 2 columns.. I'm not sure at this stage - you need to provide more code for me (in terms of the loop etc where you are wanting to show the content). –  Nathan Fitzgerald Dec 20 '13 at 12:09
    
Hey Nathan, thanks. I've changed my function, but it seems to be only working on the latest post, rather than all. –  tmyie Dec 20 '13 at 12:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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