Allow HTML in Excerpts

By default, WordPress strips all HTML tags from excerpts. To allow them, simply replace the filter that creates the excerpt from your content.

First, copy the default excerpt filter from wp-includes/formatting.php:

function wp_trim_excerpt($text) { // Fakes an excerpt if needed
    global $post;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace('\]\]\>', ']]>', $text);
        $text = strip_tags($text);
        $excerpt_length = 55;
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
            array_pop($words);
            array_push($words, '[...]');
            $text = implode(' ', $words);
        }
    }
    return $text;
}

 By changing the strip_tags parameters, you can allow whatever tags you want:

Also be sure to change the name of the function. Copy this to your functions.php file.

function lt_html_excerpt($text) { // Fakes an excerpt if needed
    global $post;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace('\]\]\>', ']]>', $text);
        /*just add all the tags you want to appear in the excerpt --
        be sure there are no white spaces in the string of allowed tags */
        $text = strip_tags($text,'<p><br><b><a><em><strong>');
        /* you can also change the length of the excerpt here, if you want */
        $excerpt_length = 55; 
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
            array_pop($words);
            array_push($words, '[...]');
            $text = implode(' ', $words);
        }
    }
    return $text;
}

 Then, replace the default filter with your new one in functions.php:

/* remove the default filter */
remove_filter('get_the_excerpt', 'wp_trim_excerpt');

/* now, add your own filter */
add_filter('get_the_excerpt', 'lt_html_excerpt');

 

Comments are closed.

Skip to toolbar