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.
Hi Mike,
Do you have code so the short code will appear in a post grid?
Thank You
Hey! If the post grid uses the proper hook it should work. What plugin are you using?
It is called Rate My Post. Thanks for your help.
Hey Brad — I wasn’t able to find any grid features in that plugin, are you sure that is what is generating your post grid? Can you send me a link to the site (you can use my contact form or post it here)
Exactly what I needed — thanks!
My pleasure! Glad you were able to find some value in it.