WordPress is the most popular platform when it comes to blogging with tons of features and tons of themes and plugins to customize it. WordPress also has widgets in themes which allows you to easily display content in sidebar or locations where widgets are supported. The most commonly used widget is text widget, you can enter any HTML text and it will display without any issues. But at the same time, one of the main problems of widgets is that PHP code is not supported although you can use text, HTML and scripts.
There are many plugins which can bring in this feature to WordPress by adding a WordPress PHP widget, but there is a simpler way to enable this feature using a simple script suggested by Emanuele Feronato. To add php code to widgets, add the below function to functions.php file in your theme.
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; }
Open the functions.php file available in your WordPress theme and add this function, save the file. This will turn the default text widget into a php enabled widget. Here is an example;
Make sure you use the correct php formatting in the widget to make the content available online.
Detailed explanation on how this function works is available here. This function is pretty handy as you do not have to increase the server load by installing another plugin to get the php functionality.
Bit risky using eval in the admin area of your site.
I’ll rather create a shortcode for the user to use in widget which is easily done by a filter http://www.paulund.co.uk/enable-shortcodes-in-widgets