How to run PHP code from Text Widget in WordPress
Surjit Singh
Experienced in developing solutions for Tour & Travel services, e-Commerce, Real Estate, e-Learning (LMS), Profile & Services CMS and custom projects based on unique business requirements.
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, i'm 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:
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);
3. Save changes
4. Navigate to Appearance->Widgets
5. Find “Text” Widget and drag it where you want the widget to be displayed
6. Write a title if you need one
7. Write any PHP code in the text area
8. Click on the “Save” button and go check the result
just try out with your widget:
<?php echo "Today is " .date("d/m/Y");?>
--
1 年i added to functions.php through these file editor but it can't save and show this error: Your PHP code changes were rolled back due to an error on line 258 of file wp-content/themes/preferential-lite/functions.php. Please fix and try saving again. syntax error, unexpected variable "$html"