-
-
Save Savantos/77f9231f707a25a3e8b6cab5e961a3cb to your computer and use it in GitHub Desktop.
WP Excerpt - allow HTML Tags in Excerpt
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
<?php | |
//ref - http://wordpress.stackexchange.com/questions/141125/allow-html-in-excerpt/141136 | |
function wpb_excerpt_allowedtags() { | |
// Add custom tags to this string | |
return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>'; | |
} | |
function wpb_custom_wp_trim_excerpt($text) { | |
$raw_excerpt = $text; | |
if ( '' == $text ) { | |
$text = get_the_content(''); | |
$text = strip_shortcodes( $text ); | |
$text = apply_filters('the_content', $text); | |
$text = str_replace(']]>', ']]>', $text); | |
$text = strip_tags($text, wpb_excerpt_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */ | |
//Set the excerpt word count and only break after sentence is complete. | |
$excerpt_word_count = 35; | |
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); | |
$tokens = array(); | |
$excerptOutput = ''; | |
$count = 0; | |
// Divide the string into tokens; HTML tags, or words, followed by any whitespace | |
preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $text, $tokens); | |
foreach ($tokens[0] as $token) { | |
if ($count >= $excerpt_length && preg_match('/[\,\;\?\.\!]\s*$/uS', $token)) { | |
// Limit reached, continue until , ; ? . or ! occur at the end | |
$excerptOutput .= trim($token); | |
break; | |
} | |
// Add words to complete sentence | |
$count++; | |
// Append what's left of the token | |
$excerptOutput .= $token; | |
} | |
$text = trim(force_balance_tags($excerptOutput)); | |
$excerpt_end = ''; | |
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); | |
$text .= $excerpt_more; /*Add read more in new paragraph */ | |
return $text; | |
} | |
return apply_filters('wpse_custom_wp_trim_excerpt', $text, $raw_excerpt); | |
} | |
remove_filter('get_the_excerpt', 'wp_trim_excerpt'); | |
add_filter('get_the_excerpt', 'wpb_custom_wp_trim_excerpt'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment