Last active
December 28, 2015 07:39
-
-
Save thisislawatts/7465826 to your computer and use it in GitHub Desktop.
WordPress Excerpt _with_ HTML tags. Based on some brilliant snippets elsewhere.
This file contains hidden or 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
/** | |
* Close out any open tags | |
* via: http://milianw.de/code-snippets/close-html-tags | |
*/ | |
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; | |
} | |
/** | |
* via: http://aaronrussell.co.uk/legacy/improving-wordpress-the_excerpt/ | |
* @uses closetags | |
*/ | |
function bookstoker_trim_excerpt($text = '') { | |
$raw_excerpt = $text; | |
if ( '' == $text ) { | |
$text = get_the_content(''); | |
$text = apply_filters('the_content', $text); | |
$text = strip_tags( $text, '<em>'); // Only allow emphasis | |
$excerpt_length = apply_filters('excerpt_length', 55); | |
$excerpt_more = apply_filters('excerpt_more', ' ' . '[…]'); | |
$words = explode(' ', $text, $excerpt_length + 1); | |
if (count($words)> $excerpt_length) { | |
array_pop($words); | |
$text = closetags( implode(' ', $words) ) . $excerpt_more; | |
} | |
} | |
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); | |
} | |
remove_filter('get_the_excerpt', 'wp_trim_excerpt' ); | |
add_filter('get_the_excerpt', 'bookstoker_trim_excerpt'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm getting an odd bug where an extra p tag is surrounding the excerpt more text.