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 46 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

/**
* 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

Simple History plugin banner

Shorten the length of the log file for Simple History plugin

Posted in , ,

The Simple History plugin default history period is 60 days. The log includes not only user initiated changes to the website, but all the automated updates to plugins, etc. This can make the log file pretty large.

(This post was viewed 8 times) in the last month.)

Read More
How to add custom post types to your default RSS feed 1

How to add custom post types to your default RSS feed

Posted in , , ,

RSS readers are somewhat old school in 2020, but the RSS feed that is part of WordPress is used by email services like Mailchimp and Mailerlite to create automated email updates when you add a new post to your website.

If you have custom post types though, they are not included in the default URL:

https://yoursite.com/feed

(This post was viewed 148 times) in the last month.)

Read More
Storing javascript in a metabox.io Custom Field textarea 2

Storing javascript in a metabox.io Custom Field textarea

Posted in , ,

For some client projects I needed to embed javascript code in a page (Post). I used a custom field textarea to insert the code when creating the Post. The problem was the default for text fields was to run them through a sanitizer.php to strip out any type of code that might be malicious. This is a good thing. But in this case it defeats the purpose.

So how to disable the sanitizing for just this field without breaking the default?

 

(This post was viewed 100 times) in the last month.)

Read More
Create a Scrolling Column with trivial CSS 3

Create a Scrolling Column with trivial CSS

Posted in ,

The client wanted to display a list of past events in a scrollable column. This was easy to implement using simple css. The page layout was done with Beaver Builder, but the solution should work for any html container.

(This post was viewed 85 times) in the last month.)

Read More
Changing a Submenu to a Mega-menu with Beaver Builder 4

Changing a Submenu to a Mega-menu with Beaver Builder

Posted in , , ,

Sometimes you want to present a navigation menu as a horizontal “mega-menu” instead of a hierarchal dropdown menu. This is really simple if you are using Beaver Builder. The mega-menu feature is built in, but is unfortunately hidden. You have to know the secret to turn it on.

(This post was viewed 100 times) in the last month.)

Read More
Formatting a custom number field to add commas 5

Formatting a custom number field to add commas

Posted in , , , ,

I needed to format a number field (999,999,999), coming from a custom field number-format (no other characters permitted in the number entry field). No “$” no commas or decimal points, etc. to output as a normal currency format.

Formatting a custom number field to add commas 6

When displaying the number I could add a “$” in front of the number, but couldn’t find a way to format the number since you can’t do that with CSS.

(This post was viewed 255 times) in the last month.)

Read More

Popular Posts


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

Leave a Reply

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