the_excerpt() or get_the_excerpt with shortcode escape

I have few posts which have a dropcap shortcode wrapped around the first character like so:

[dropcap]T[/dropcap]his is a dropcap. 

The replacement for this shortcode yields:

Read More
<span class="dropcap">T</span>his is a dropcap.

However, when I call the_excerpt() or get_the_excerpt() on these posts, its returning:

"his is a dropcap".

I need it to return “This is a dropcap” as if no shortcode exists.

Related posts

Leave a Reply

2 comments

  1. You can make WordPress execute your shortcode in the excerpt by hooking into get_the_excerpt filter and overwriting the default wp_trim_excerpt function, which is responsible of stripping the shortcode tags from the excerpt as pointed by Chip:

    add_filter('get_the_excerpt', 'do_my_shortcode_in_excerpt');
    function do_my_shortcode_in_excerpt($excerpt) {
        return do_shortcode(wp_trim_words(get_the_content(), 55));
    }
    

    This is applied to both the_excerpt() and get_the_excerpt() outputs. If you want to apply it only for the_excerpt() output, hook to the_excerpt filter:

    add_filter('the_excerpt', 'do_my_shortcode_in_excerpt');
    function do_my_shortcode_in_excerpt($excerpt) {
        return do_shortcode(wp_trim_words(get_the_content(), 55));
    }
    
  2. The the_excerpt() function doesn’t parse shortcodes. WordPress actually strips the entire shortcode from the excerpt. Since the “T” is wrapped in a shortcode, it doesn’t get output by the_excerpt().

    The easiest solution is probably to create a custom excerpt, via the Post Excerpt meta box on the Edit Post screen, for posts in which you use the Dropcap shortcode.

    The better solution is probably to ditch a shortcode that exists solely to do something that can reliably be done using nothing more than CSS rules.