Shortcodes are a very popular feature in WordPress that allows you to add custom functionality to the content. WordPress also has some built-in shortcodes on its own. They are very easy to use inside the posts or pages and they even work inside the Text Widget. But they won’t work when they are added in an excerpt or a custom field. This article will show you how to use shortcodes in those cases too.
Let’s first examine, how to make shortcode work in the excerpt field, when we are inside the post or page editor.
Enable shortcodes in Excerpts
We can enable the shortcode in the excerpt by adding the following line inside the functions.php
of our theme:
add_filter('get_the_excerpt', 'do_shortcode');
The above code will process a shortcode when the_excerpt() or get_the_excerpt() function is used in the theme.
But, what if on the other hand we only wanted this functionality on specific get_the_excerpt call in a theme and nowhere else? To do this, we would wrap it with the do_shortcode function, like so:
echo do_shortcode(get_the_excerpt());
In the above line, the content of the excerpt is first run through do_shortcode() function which processes any shortcode it finds.
Enable shortcodes in Custom Fields
Sometimes, we might want to use a shortcode as a value in the custom field. Usually, the value of that custom field is obtained in the theme using get_post_meta function, so all we need to do is to wrap it by do_shortcode function, like this:
echo do_shortcode(get_post_meta(get_the_ID(), "MyCustomField", true));
In the above example, the name of the custom field is MyCustomField. Change that to the name of your custom field.
Enable shortcodes in various plugins
There will be instances, where we want to use a shortcode in a field of a specific plugin. If this plugin supports filters, we can use those filters to wrap the output with the do_shortcode function similar as we did with the excerpt and the custom field. To learn more, check our other article in which we use the same technique to enable shortcodes on a very popular WordPress Contact Forms 7 plugin.
Conclusion
To use shortcodes inside excerpts and custom fields in WordPress, we need to add a bit of code. For excerpt fields, we need to either add a specific filter in functions.php
theme file, or we wrap the instances of get_the_excerpt() in the theme with the do_shortcode() function. For custom fields, we again used the same do_shortcode function.