How to Include HTML in Excerpts?

I use the Leaf theme

and I can’t seem to format the home page excerpts.

Read More

I tried plugins and fiddling around with the theme-functions.php file but to no avail.

I don’t need a lot of fancy stuff in the excerpts just a bit of formatting, nothing more.

That should be possible, right?

Related posts

1 comment

  1. The excerpt is created in -> wp-includes/formatting.php with this code:

    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;
    }
    

    To change the behavior WP exhibits normally for excerpts, first remove this function (not from the core code, but using remove_filter() by placing this in your functions.php:

    remove_filter('get_the_excerpt', 'wp_trim_excerpt');
    

    Next, you’ll need to create a new function to control excerpts so you can copy the above function from WP core as a starting point. Name it something different. Then, change what you need. For example, if you want to allow the tag in your excerpts, you would modify this line:

    $text = strip_tags($text);
    

    to this:

    $text = strip_tags($text, '<b>');
    

    If you need more than one allowed html tag, list them after . So your new function in your functions.php might look like:

    function nb_html_excerpt($text) {
        global $post;
        if ( '' == $text ) {
            $text = get_the_content('');
            $text = apply_filters('the_content', $text);
            $text = str_replace(']]>', ']]&gt;', $text);
            $text = strip_tags($text, '<b>');
            $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;
    }
    

    And then finally, you need to tell WP to filter your excerpt through your new function. Add the filter like this in functions.php:

    add_filter('get_the_excerpt', 'nb_html_excerpt');
    

Comments are closed.