Executing php inside a WordPress widget

Executing php inside a WordPress widget without any plugin

Sometimes in your WordPress theme you need to execute custom php code in a widget, because you want to display different information according to the category you are in, or simply because you need to execute a php script into that widget.
There are a lot of plugins doing this task, adding a new type of widget generally called “php widget”, but rather than installing a plugin this simple job can be done simply adding in functions.php file of your theme these few lines:
/*-------------------------  START -------------------------------------*/
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;
}

/*---------------------------- END ----------------------------------*/ 

Which will turn the default Text widget into a php enabled widget.
Adding this feature directly to functions.php allows you to create a theme with this built in feature without the need of an external plugin.

No comments:

Post a Comment