Skip to content

Instantly share code, notes, and snippets.

@DanielFloeter
Last active October 30, 2016 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielFloeter/b713a024790cef7c566473b2239bd5cd to your computer and use it in GitHub Desktop.
Save DanielFloeter/b713a024790cef7c566473b2239bd5cd to your computer and use it in GitHub Desktop.
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