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;
}
You can use this function:
and then call it in your loop with:
The magic part your looking for is wpautop, a WordPress function, which will convert double line-breaks in the text to proper paragraphs.
With wpautop in place, you can then use the PHP function substr to get the first paragraph starting at the first character until it reaches the first closing paragraph, and then add 4 characters so that the closing tag is not stripped.
To further expand on this, if you want to then get everything except for the first paragraph you can use this complementary function which will start at the end of the first closing paragraph tag and get everything after it:
and call it in the loop with:
Try this: