WordPress Execute PHP Code Snippet

Want to execute PHP in a WordPress text widget? Yet another helpful snippet!

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;
}

UPDATE 9/12/2011: The prior code I was using here wasn’t cutting it for some reason – thanks to Emanuele Feronato for this awesome chunk of code!

Just add this to your theme functions.php file to automatically execute PHP in WordPress text widget. I had run across a plugin back when I started working in WordPress that would do this, but let’s face it, it’s yet one more plugin. And if I remember correctly, it didn’t work quite right or predictably.

Happy Friday!  Hope everyone does well against Hurricane Irene!

Author: Eric Erickson

Share This Post On

Submit a Comment

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