Add PHP to a WordPress widget

Add PHP to a WordPress widget

Here’s a useful little function for enabling PHP in the standard WordPress text widget.

//enable php in text widget
add_filter('widget_text','execute_php',100);

function execute_php($html){
 if(strpos($html,"<"."?php")!==false){
 ob_start();
 eval("?".">".$html);
 $html=ob_get_contents();
 ob_end_clean();
 }
 return $html;
 }

It’ll look for the ‘<?php’ opening tag and the ‘?>’ closing tag and treat everything in it as PHP, rather than HTML. This is a huge advantage when trying to add WordPress specific PHP to pages without resorting to modifying the templates. I originally came across it here.

Just add the code to your child theme’s functions.php. If you’re not using a child theme, why not? Get one here in seconds for free.

Be sure to subscribe for more helpful code drops, tutorials and resources.

Stephen James

SJ is a web developer living in the coastal town of Southsea, England. He is a Divi and WordPress advocate and the founder of Divi Space.