Allow Shortcode for Custom Widget in WordPress
WordPress provides various default Widgets that you can use on your WordPress site. Some of the default widgets are “Recent Posts”, ” Recent Comments “, “Search“, “Categories“, etc. These widgets come with every installation of WordPress. One of the most commonly used widgets is “Text-Widget“. It allows users to add HTML tags, images, videos and of course texts too. You can also add your HTML snippets inside the Text Widget area to display on your site. You can use Shortcode in text-widget too, but you need to add a small code in your active theme’s functions.php file. Add this simple snippet on the top of your functions.php file (or anywhere inside functions.php ).
add_filter('widget_text', 'do_shortcode');
However, if you are creating your Custom WordPress Widget and want to display shortcode in your widget, the above filter code certainly wouldn’t work.
Shortcode is a simple physics of WordPress. It lets you do big things in less effort.. Share on XYou may want to allow shortcode for a custom widget in WordPress. For that, you’ll need to write another small snippet inside your Custom Widget code.
function custom_widget_shortcode( $text, $instance ) {
// Allows shortcodes only for the widget with the following title:
$title = 'Title Name';
remove_filter( current_filter(), __FUNCTION__ );
if( isset( $instance['title'] ) && mb_strtolower( $title ) === $instance['title'] )
$text= do_shortcode( $text );
return $text;
}
add_filter( 'widget_text', 'wpse_widget_shortcode', 99, 2 );
Now, if you insert the shortcode inside your custom widget, then it will display the shortcode. If you have any question or suggestion, feel free to comment. 🙂