Adding PHP code in Text Widget without using a Plugin.


Sometimes in our WordPress theme we need to execute PHP scripts in a text widget. However
by default WordPress doesn’t comes with this feature.

To enable PHP code within WordPress widget we can use few plugins like PHP text widget and PHP Code Widget.
Since installing another plugin might slow the site down, this task can be also be accomplished by adding the following code to the functions.php file :

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;

This very helpful code was written and very well eplained on Emanuele Feronato’s blog:
emanueleferonato.com

Leave a Reply

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