How To Use A Shortcode Inside A Post Excerpt

Using a shortcode inside post content is a fairly simple task. Simply write out the shortcode inside some brackets and you’re all set. But what if you wanted to use a shortcode inside a post excerpt? If you’ve tried to do this yourself you’ll quickly realize that this feature is not available by default.

So, how do we get WordPress to parse shortcodes that are present inside the post excerpt? We hook into the get_the_excerpt filter and tell it to parse any shortcodes it finds:

add_filter( 'get_the_excerpt', 'my_shortcode_parser' );
function my_shortcode_parser( $excerpt ) {
    return do_shortcode($excerpt);
}

This short snippet of code can be placed inside your theme’s functions.php file.

Here is a breakdown of what the code is actually doing:

add_filter( 'get_the_excerpt', 'my_shortcode_parser' );

This line of code hooks into the get_the_excerpt filter hook provided by WordPress. We pass the name of our custom function as the second parameter.

function my_shortcode_parser( $excerpt ) {
    return do_shortcode($excerpt);
}

Here we set up our custom function called my_shortcode_parser. It will accept a single parameter which will contain the text of the actual excerpt. All we have to do now is return exactly what we want for the excerpt text. In our case, we’re going to parse any shortcodes present in the text using do_shortcode and simply return the same content but with all shortcodes parsed.

Now you’ll be able to use shortcodes in all your post excerpts.