How to run PHP code from Text Widget in WordPress

Text Widget is one of the most popular widgets which comes with WordPress. This widget allows you to enter text, add images, videos, lists and much more in the text area which can be displayed on the sidebar or in the footer of your website.

Instead of adding basic text and media files, you can write HTML code which will be executed. Also, most of the social media code which is needed for displaying followers, popular articles on social networks and similar will be shown in the Text Widget without a problem.

But, if you’re trying to run PHP code directly from the widget, you’ll run into a problem. Text Widget isn’t designed to execute the code. You will find your code being stripped and shown as is.

In this article, we’re about to show you how to override this without using a plugin. After you store the code into your theme, you will be able to use any PHP code in the widget and, you guessed, WordPress will recognize it and run the code!

  1. Open functions.php file
  2. Copy and paste the following code:
  3. function php_execute($html){
    if(strpos($html,"<"."?php")!==false){ ob_start(); eval("?".">".$html);
    $html=ob_get_contents();
    ob_end_clean();
    }
    return $html;
    }
    add_filter('widget_text','php_execute',100);
  4. Save changes
  5. Navigate to Appearance->Widgets
  6. Find “Text” Widget and drag it where you want the widget to be displayed
  7. Write a title if you need one
  8. Write any PHP code in the text area
  9. Click on the “Save” button and go check the result


Just to try out the function, you can try to display simple text via PHP:

echo 'Wow, this function really works! Thanks, FirstSiteGuide!' ?>

Yeah, we’re that subtle when it comes to thanking ourselves. In the other example, you can try to display current date with PHP without saying thanks:

echo "Today is " . date("d/m/Y");

Yes, that simple function was enough to change the way WordPress sees the PHP code in the Text Widget. But, while this function will let you execute PHP code in the widget area, it won’t let you do the same in your post and pages.

This was just one of the interesting WP tutorials. If you liked it, learn more about WordPress and level up your webmaster skills with our other resources.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

8 thoughts on “How to run PHP code from Text Widget in WordPress

Leave a Reply

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