Last updated: July 18, 2017
How to

Enable Shortcodes inside Excerpts, Widgets & Custom Fields in WordPress

Shortcodes are a very popular feature in WordPress that allows you to add custom functionality to the content. We can use a shortcode inside the post or a page, but they won’t work when they are added in a widget, an excerpt or a custom field. This article will show you how to fix this problem.

Let’s first examine, how to make shortcode work in the excerpt editor.

Enable shortcodes in Excerpts

We can enable the shortcode in the excerpt by adding the following line inside the functions.php:

add_filter('get_the_excerpt', 'do_shortcode');

If on the other hand, we only want to this functionallity in specific template file, we would display the excerpt to that template file like so:

echo do_shortcode(get_the_excerpt());

The above line runs the content of excerpt through do_shortcode function and echoes the result.

Enable shortcodes in Text Widgets

To enable shortcode in a widget, we add this inside the functions.php file:

add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );

In line 1, we make sure that the shortcode are not automatically wrapped in paragraph tags <p></p> and in line 2, the do_shortcode function will render any shortcodes it finds in text widgets.

Using a plugin

There is also a plugin available Classic Text Widget that adds a text widget with the shortcode support. Note that this widget lacks the TinyMCE visual editor.

Enable shortcodes in Custom Fields

To make shortcodes available for specific custom field anywhere in the theme, we add the following code inside functions.php:

function enable_shortcode_in_customfield( $meta_value, $post_id, $meta_key, $single ) {
  if( 'MyCustomField' == $meta_key )
  {	
	  	$meta_value = do_shortcode($meta_value[0]);
  }	
	return $meta_value;
}
add_filter('get_post_metadata', 'enable_shortcode_in_customfield', 10, 4);

In the above example, the name of the custom field is MyCustomField. Change that to the name of your custom field.

And if we want to use shortcode only in a specific template file, we could simply do this:

echo do_shortcode(get_post_meta(get_the_ID(), "MyCustomField", true));

Here, we get the value of custom field using get_post_meta function and that value is then processed with do_shortcode function.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.