Created
October 22, 2013 00:07
-
-
Save chasereeves/7093097 to your computer and use it in GitHub Desktop.
wordpress: Get first paragraph (first two if paragraph #1 isn't long enough).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//=========================================================== Grab first paragraph (two if first is not long enough) | |
function get_first_two_paragraphs(){ | |
global $post; | |
$str = wpautop( get_the_content() ); | |
$psToGrab = 2; // number of paragraphs to get | |
$maxFirstParaLength = 200; // character max in first paragraph | |
$matches = array(); // matching elements will go here | |
$pattern = '%<p[^>]*>(.*?)</p>%i'; // match what's between all <p> tags | |
preg_match_all($pattern, $str, $matches); // do the regex match | |
$outparts = array_slice($matches[1], 0, $psToGrab); // chop off everything after the first 2 elements | |
foreach($outparts as $part) { | |
$toKeep = "<b><strong><em>"; | |
$out .= strip_tags($part, $toKeep).' '; | |
if(strlen($out) > $maxFirstParaLength) { | |
break; | |
} | |
} | |
return $out; | |
} | |
// To use in template: <?php echo get_first_two_paragraphs(); ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment