How To Execute PHP Code in WordPress Text Widget

Have you tried to execute PHP code in WordPress widget? If you did then you must be aware of the fact that PHP code doesn’t work in WordPress text widget.

There is no way you can directly add PHP code in any WordPress widget. But if you want to do so, you can make use of a Plugin called ‘Executable PHP Widget’ or just follow the steps given below.

In this post, i’ll show you how to execute PHP code in WordPress text widget without using any plugin. For this you need to edit the functions.php file of your WordPress theme.

You can find this file by browsing through –

Admin Dashboard > Appearance > Editor > Functions.php

Just copy paste the code given below at the end of the file and save the file.

[php]

add_filter(‘widget_text’,’codefap_execute_php’,99);
function codefap_execute_php($html){
if(strpos($html,”<“.”?php”)!==false){
ob_start();
eval(“?”.”>”.$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}

[/php]

Now try and add PHP code to the default text widget in WordPress. Now it should definitely work!

Additional Info

add_filter is nothing but just a WordPress hook which helps to modify variety of text before sending it out to the browser. We are adding a hook to the filter called widget_text with help of function codefap_execute_php and priority is 99. And in this case 99 will return a low priority because numbers with lower value have higher priority.

In the function codefap_execute.php, we are trying to determine whether the html code contains <?php string. If it does then we call ob_start(). The ob_start function basically turns on output buffering. This means the text produced by text widget is temporarily saved in some internal buffer.

Then we evaluate html produced as a PHP script. Finally get the contents from output buffer, clean the output buffer, turn it off and return the produced output.

For more amazing posts, Subscribe to CodeFap Blog Feed.

Leave a Reply