Applying Styling to a Post Excerpt

There, I Fixed It! is a small blog I’ve created, mostly for myself. It includes fixes for bizarre, specific and unique problems that I’ve had a hard time finding answers to. They are mostly fixes for WordPress and Elementor related plugins and issue. These are only my fixes that worked for me in specific instance.  This is not a support or discussion blog. Do not contact me with questions.

Do you want your embedded post excerpts to actually have styling, like bold, italic, breaks and paragraph? Base WordPress assumes you don’t. They are wrong. But you’ve got two options. 

One is to install the Advanced Excerpts plugin. I’ve had this not work at all on some Elementor sites, though it has worked perfectly for years on other WordPress sites.

The other thing you can do is add the following code to your theme child’s function.php file. I got the code from the bottom of this stackexchange page and it works a treat! You can add extra tags that you want to view and also how long the excerpt should be.

				
					{
    $raw_excerpt = $text;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);

        // Removes any JavaScript in posts (between <script> and </script> tags)
        $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);

        // Enable formatting in excerpts - Add HTML tags that you want to be parsed in excerpts, default is 55
        $text = strip_tags($text, '<strong><b><em><i><a><code><kbd><br><p>');

        // Set custom excerpt length - number of words to be shown in excerpts
        $excerpt_length = apply_filters('excerpt_length', 150);

        // Modify excerpt more string at the end from [...] to ...
        $excerpt_more = apply_filters('excerpt_more', ' ' . '...');

        $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
        if ( count($words) > $excerpt_length ) {
            array_pop($words);
            $text = implode(' ', $words);

            // IMPORTANT! Prevents tags cutoff by excerpt (i.e. unclosed tags) from breaking formatting
            $text = force_balance_tags( $text );

            $text = $text . $excerpt_more;
        } else {
            $text = implode(' ', $words);
        }
    }
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

// Remove the native excerpt function, and replace it with our improved function
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'better_trim_excerpt');