Enable Shortcode and PHP support in WordPress Text Widget

Every WordPress install is bundled with a number of default Widgets such as Pages (A list of your site’s Pages), Search (A search form for your site), Archives (A monthly archive of your site’s posts), Calender, Text etc.
Our main focus is on the Text widget that only parse arbitrary text and HTML codes.
In this article, i will show us how to make the Text widget parse not just text and HTML, but also PHP and Shortcodes.

Enabling Shortcode support

The code below will enable shortcodes support for Text widget.


add_filter('widget_text', 'do_shortcode');
Enabling PHP support

Executing PHP in Text widget is made possible by PHP eval language construct.


        function php_support_text_widget($text) {
	ob_start();
	eval('?>'.$text);
	$text = ob_get_contents();
	ob_end_clean();
	return $text;
	}
	add_filter('widget_text', 'php_support_text_widget');
	}

To use the codes, paste them to your theme’s function.php file or in an activated dummy plugin.

Note: ensure the PHP code to be executed is encapsulated in between PHP opening and closing tag <?php … ?>

WordPress Text Widget

Executed PHP and shortcode in Text Widget

The Plugin

For the purpose of this tutorial, i released a WordPress plugin Enable Shortcode and PHP in Text widget.
To enable shortcode and PHP support in Text widget, go to the plugin settings page and check the options.

Plugin settings of Enable Shortcode and PHP in Text widget

Plugin ha sido traducida al español por Andrés de WebHostingHub.com

No need using the code snippets above if you have the plugin installed and activated.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address