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.
1 |
ave you found that WordPress strips shortcodes... |
When WordPress converts this into an excerpt, you end up with
1 |
ave you found that WordPress strips shortcodes... |
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 ]
1 2 3 4 5 6 |
add_filter( 'get_the_excerpt', 'shortcodetext_in_excerpt' ); function shortcodetext_in_excerpt( $excerpt ) { $more = ' <a href="'. get_permalink( get_the_ID() ) . '">more...</a>'; $content = wp_trim_words( get_the_content(), 50, $more ); return preg_replace( '/\[[^\]]+\]/', '', $content ); } |
1 2 3 4 5 |
add_filter( 'get_the_excerpt', 'shortcodetext_in_excerpt' ); function shortcodetext_in_excerpt( $excerpt ) { $content = wp_trim_words( get_the_content(), 50 ); return preg_replace( '/\[[^\]]+\]/', '', $content ); } |
Perfect fix – Thanks – I was looking for this!