Enable PHP In WordPress Widgets

- - Wordpress

The default Text Widget in WordPress allows you to insert arbitrary Text and/or HTML/CSS code but how does one

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. If access to the filesystem is an issue for you this nifty trick will be a life saver.

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.

Only users with the unfiltered_html role will be allowed to insert unfiltered HTML. 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);


Once you insert the above code inside of your functions.php file located in the themes folder, you can start embedding php snippets inside of your widgets. An alternative to this is installing a plugin called PHP Code Widget.

Post Tags:
Join the Newsletter

Sign up for our personalized daily newsletter

Kodesmart

#1 GUIDE TO DRUPAL, WORDPRESS, CSS AND CUSTOM CODING | BEGINNER TO PRO