WordPress : Keep excerpt shortcode contents

Have you found that WordPress strips excerpt shortcodes in your blog posts? The excerpt is a special field associated with each WordPress post intended to provide a teaser. However, managing a separate excerpt for every blog post can become tedious, so WordPress offers a way of providing an excerpt on the fly by taking the first 55 words and using that as the excerpt.

The problem with this is that the standard WordPress functions that return the excerpt, the_excerpt() and get_the_excerpt(), both strip out all shortcode tags. Actually they don’t just strip out your excerpt shortcode, they actually tear about everything in-between opening and closing shortcode tags as well.

The example below shows that the first line looks like in the wordpress visual editor.

When WordPress converts this into an excerpt, you end up with

Creating a better excerpt

The answer is to hook into WordPress’ add_filter function. You just need to add the following code to your theme’s functions.php file. This will create a new excerpt by using the wp_trim_words function. Then we simply pluck out [ and ] and anything inbetween them with preg_replace. The regex does this:

[ this will be removed ] this will not be removed [ this will be removed ] Because the above function will run after the filter excerpt_more would run, the only way to modify the $more element is within our new function itself. If you just want your excerpt to end with the default elipse … then just use the following instead:
This article was current as of WordPress 3.8 but should be fine right back to WordPress 2.8 (I think!)

, , ,

One Response to WordPress : Keep excerpt shortcode contents

  1. Karena July 9, 2014 at 16:00 #

    Perfect fix – Thanks – I was looking for this!

Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.