How to Enable PHP In WordPress Widgets

First of all enabling PHP code to execute from inside widgets can save us plenty of time to do tasks that would usually involve connecting to the backend.

The code below allows WordPress to parse any PHP code in the text widget and executes it. All PHP code must first be enclosed in the standard php opening and closing tags ( ) for it to be recognized and executed however.

See also  Display WordPress Theme Feature Image

This includes PHP code, so users without admin or editor permissions will not be able to use this method to embed and execute php code, even if they have widget editing permissions.

// allow php in wp widgets
function execute_php($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',100);

Leave a Reply

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