Overwriting wordpress get_the_excerpt to keep html tag

For anyone who’s trying to customize your wordpress theme and wonder how to get a chunk of your post contents, maybe first xx characters of your post, and display them on your homepage. WordPress comes with a function  called get_the_excerpt which will do exactly what you want BUT it will remove all your html tag.

For example, here’s how my post content looks like.

Screen Shot 2557-02-16 at 1.38.58 PM

You’ll see that there are new lines <br/> and paragraph <p> in my content. However, when I use get_the_excerpt in my homepage. It turns out like this.

Screen Shot 2557-02-16 at 1.38.44 PM

As you can see, all new lines and paragraph are removed and my content are displayed in simple text format.

So, how to prevent this? Here’s how.

Open you functions.php in your theme folder and add this function

Screen Shot 2557-02-16 at 1.46.27 PM

This is to create a new function for excerpting. The magic line is strip_tag. I put only <p> here but you can put whatever tag you want. For example, you can use strip_tag($text,'<p><img>’) to get your img as well.

But just adding this function won’t work because get_the_exceprt() is still wiring to the old function. So you’ll need to add two extra lines to your theme functions.php

Screen Shot 2557-02-16 at 1.48.09 PM

This is to tell wordpress that when you call get_the_exceprt. You are going to call your own improved_trim_exceprt, not the wp_ one.

This is how it looks like after fixing. You can see that new lines and paragraph are now interpreted correctly.

Screen Shot 2557-02-16 at 1.56.27 PM

One thing worth noting is that this will affect every get_the_excerpt in your code, and usually, there are more than one place. For example facebook sharing (og:description) might also use get exceprt as description when sharing to facebook and you may want to remove html tag before doing so (because it looks like crap with html tag). To work around this, you might want to create more than one custom excerpt function.

Below are example of my custom functions.

Screen Shot 2557-02-16 at 1.54.37 PM

btw. I’m starting my new site which is an example in this post. Feel free to visit.

2 thoughts on “Overwriting wordpress get_the_excerpt to keep html tag

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s