Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Excerpt allow HTML
<?php
// Show sharing buttons, e.g. from Jetpack
// http://tiptoppress.com/allow-html-in-excerpt-becomes-filteractions-code/
// TODO: Rewrite code as filter hook
// TODO: Multi select supported HTML elements in option (https://github.com/tiptoppress/category-posts-widget/issues/59)
function widget($args, $instance) {
...
add_filter('the_excerpt', array($this,'allow_html_excerpt'));
...
// do post loop
// call the excerpt method
the_excerpt();
...
remove_filter('the_excerpt', array($this,'allow_html_excerpt'));
...
}
/**
* Excerpt allow HTML
*/
function allow_html_excerpt($text) {
global $post, $wp_filter;
$new_excerpt_length = ( isset($this->instance["excerpt_length"]) && $this->instance["excerpt_length"] > 0 ) ? $this->instance["excerpt_length"] : 55;
if ( '' == $text ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace('\]\]\>', ']]&gt;', $text);
$text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);
$cphtml = array(
'&lt;a&gt;',
'&lt;br&gt;',
'&lt;em&gt;',
'&lt;i&gt;',
'&lt;ul&gt;',
'&lt;ol&gt;',
'&lt;li&gt;',
'&lt;p&gt;',
'&lt;img&gt;',
'&lt;script&gt;',
'&lt;style&gt;',
'&lt;video&gt;',
'&lt;audio&gt;'
);
$allowed_HTML = "";
foreach ($cphtml as $index => $name) {
if (in_array((string)($index),$this->instance['excerpt_allowed_elements'],true))
$allowed_HTML .= $cphtml[$index];
}
$text = strip_tags($text, htmlspecialchars_decode($allowed_HTML));
$excerpt_length = $new_excerpt_length;
if( !empty($this->instance["excerpt_more_text"]) ) {
$excerpt_more = $this->excerpt_more_filter($this->instance["excerpt_more_text"]);
}else if($filterName = key($wp_filter['excerpt_more'][10])) {
$excerpt_more = $wp_filter['excerpt_more'][10][$filterName]['function'](0);
}else {
$excerpt_more = '[...]';
}
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, $excerpt_more);
$text = implode(' ', $words);
}
}
return '<p>' . $text . '</p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.