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.
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.
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
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
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.
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.
btw. I’m starting my new site which is an example in this post. Feel free to visit.