A bit of PHP to preserve html formatting in standard WordPress excerpts

Code Snippet Related Categories

Reason for needing the Code Snippet

If you don’t use the Excerpt field in your posts and rely on WordPress to grab the first few dozen words of your post content what you usually find is the excerpt when displayed on the front end (usually in some sort of archive or post grid display) will have most of the html tags removed leaving you with a single block of plain text.

If I go to the bother of formatting my post content to make it more interesting and easier to read and understand I’d like that formatting to be preserved even in that post’s excerpt.

(This post was viewed 2,768 times) in the last month.)

What the Code Snippet does

This bit of php code, put in your functions.php file does the trick. It's well commented so you know what it's doing and is pretty easy to tweak. This gives you nicely formatted content in your post excerpts and RSS feeds too.

The html tags I've chosen to include in excerpts are:
<strong><b><em><i><a><code><kbd><p><br><ul><ol><li><img><blockquote>

What the page looks like Before and After

Here's the Code Snippet

The following is an updated version that appears to work better with WordPress 6.x and Full Site Editing Block themes:

function filter_post_excerpt_attrs( $metadata ) {
    if ( 'core/post-excerpt' === $metadata['name'] ) {
        $metadata["attributes"]["excerptLength"] = false;
    }
    return $metadata;
};

add_filter( 'block_type_metadata', 'filter_post_excerpt_attrs', 10 );

 

Below is the original code that doesn't seem to work with current WordPress and FSE Block themes - try the above code instead.

/**
* allow formatted text in excerpts
**/
function better_trim_excerpt($text)
{
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]&gt;', $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><p><br><ul><ol><li><img>');

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

// 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');

I found this code at the bottom of this page: wordpress.stackexchange.com

Limit search for phrases by using " " around the phrase

Subscribe to Code Snippet updates

You will get an email the morning after we post a new Code Snippet

Something went wrong. Please check your entries and try again.

Other Recent Code Snippets

WordPress site migration, copying your site and moving it 1

WordPress site migration, copying your site and moving it

Posted in , , , , ,

There are several reasons why you might want to copy your website,

you want to make a “sandbox” copy to experiment on, without affecting the public-facing production site
you want to change hosting companies to get a better deal, faster performance or more functionality
having a complete copy of your website is a great insurance policy should something happen to your host and your site is lost.

Read More
Are your website pages loading slowly? This might help... 2

Are your website pages loading slowly? This might help…

Posted in , , , , ,

Jetpack Photon should help I recommend Jetpack-Photon module (deactivate all the other Jetpack modules you don’t use). Photon is an image-only CDN solution using Automatic’s servers. All your images are uploaded to their servers the next time the image is served after you activate Photon. Subsequently the images are served […]

Read More
2-column videos test 3

2-column videos test

Posted in , ,

Using column shortcodes to make 2 columns didn’t work for this post. But I was able to do this on a Page (instead of a Post) using the theme’s 2-column page template.

See the succesful results at: Multi-column video test page

Read More
It's OK to go ahead now... WARNING! Don't update BackWPup plugin to version 3.x yet It's OK to go ahead now... 4

It's OK to go ahead now… WARNING! Don't update BackWPup plugin to version 3.x yet It's OK to go ahead now…

Posted in , , , ,

BackWPup plugin developer, Daniel Huesken has decided to begin offering a “Pro” version beginning with version 3.0 of the plugin. I don’t have a problem with this and in some cases might recommend the Pro version to some of my clients. All the issues I had with the switch to version 3.0 […]

Read More

Markup: HTML Tags and Formatting

Posted in

Headings Header one Header two Header three Header four Header five Header six Blockquotes Single line blockquote: Stay hungry. Stay foolish. Multi line blockquote with a cite reference: People think focus means saying yes to the thing you’ve got to focus on. But that’s not what it means at all. […]

Read More
I Am Worth Loving Wallpaper

Markup: Image Alignment

Posted in

Welcome to image alignment! The best way to demonstrate the ebb and flow of the various image positioning options is to nestle them snuggly among an ocean of words. Grab a paddle and let’s get started. On the topic of alignment, it should be noted that users can choose from […]

Read More

Pieter Hartsook

WordPress website coaching, design, implementation, support, and training. Background in Marketing Research and Communications. See my profile at: https://www.linkedin.com/in/hartsook/

Reader Interactions

Comments

  1. I think that depends on where the Read More link is supposed to appear, and what underlying framework you’re using to display the excerpt. I use Beaver Builder for most of my projects and using this code snippet I still see the Read More link on post archive (query loop) pages.

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to content