Connect with us

How to Execute PHP in WordPress Text Widgets without any Plugins


Wordpress

How to Execute PHP in WordPress Text Widgets without any Plugins

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.

wplogo-hoz-cmyk

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;

Widget

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.

Continue Reading
Advertisement

Nirmal is a Technology Blogger and a Microsoft MVP in Windows. He can be contacted at nirmal@nirmaltv.com. You can find Nirmal on , and .

2 Comments

2 Comments

  1. Pingback: Cómo ejecutar código PHP en los widgets de Wordpress sin plugins | Punto Geek

  2. Paul

    February 8, 2013 at 3:50 am

    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

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

More in Wordpress

Recent Articles

Advertisement

Trending Articles

Latest in Windows 10

Subscribe to YouTube Channel

Like Us on Facebook

Sponsors

sponsors
To Top