How to execute PHP code in Text Widget without using Plugin.

By default, WordPress doesn’t allow you to execute the PHP code within the text widget. But, you can easily fix this problem by adding a small amount of code to your functions.php file.

To enable PHP code within WordPress text widget, paste the following code in your functions.php file located inside your theme directory.

//Execute PHP code in WordPress text widget
function execute_php_text_widget($html){
	if(strpos($html,"<"."?php")!==false){ 
		ob_start(); 
		eval("?".">".$html);
		$html=ob_get_contents();
		ob_end_clean();
	}
	return $html;
}
add_filter('widget_text','execute_php_text_widget',100);

Now, to test whether the code is working correctly or not, paste a simple Hello World! program inside a text widget.

//Hello World
<?php echo "Hello World!" ?>
execute php code inside a WordPress text widget without using a plugin

Execute php code inside a WordPress text widget without using a plugin

If you have done everything correctly, you will be able to see the output similar to one shown in the image below,

execute php code inside a WordPress text widget without using a plugin

Execute php code inside a WordPress text widget without using a plugin

Useful Read: How to Use Shortcodes in WordPress Text Widgets?

2 Comments

  1. I have a question – WordPress normally doesn’t allow this due to security reasons. Would enabling something like this in a text widget leave the site more vulnerable to attacks versus if we left the widget’s sanitization in place where it doesn’t allow code?

    Reply

Leave a Comment.