Skip to content

Instantly share code, notes, and snippets.

@andrewlaskey
Created October 7, 2013 23:46
Show Gist options
  • Save andrewlaskey/6877006 to your computer and use it in GitHub Desktop.
Save andrewlaskey/6877006 to your computer and use it in GitHub Desktop.
Output a post excerpt with out a link and with a specific character limit in Wordpress
<?php
function limit_content($text,$numChar){
$length = $numChar;
if(strlen($text)<$length+10) return $text;//don't cut if too short
$break_pos = strpos($text, ' ', $length);//find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . "…";
}
/** * close all open xhtml tags at the end of the string
* * @param string $html
* @return string
* @author Milian <mail@mili.de>
*/
function closetags($html) {
#put all opened tags into an array
preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1]; #put all closed tags into an array
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
# all tags are closed
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
# close tags
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)){
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]); }
} return $html;}
?>
<p class="limited-content"><?php echo closetags(limit_content(preg_replace("/\[caption .+?\[\/caption\]|\< *[img][^\>]*[.]*\>/i","",get_the_content(),1),300)); ?></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment