To execute php code in WordPress has been pretty much awesome for me. Sometimes you need to execute php code in a widget to display some sort of useful information accordingly, or simply you want to execute a php script in that widget.
There are hell lot or WordPress plugins available in WordPress repo to execute php code but I prefer not to install any plugin for this, instead this simple job can be dome by adding in functions.php file of your WordPress theme these few simple lines :
This simple code has the ability to turn a text widget to a php enable widget. You know what is the best thing to add this code in your WordPress theme is that it allows you to create a theme with this built in feature without installing a plugin. This is extremely useful when you want to distribute your theme.
Wondering How It Works?
Line 1 : add_filter hooks a function to a specific filter action.
Filters are the hooks that WordPress launches to modify text of various types before it is added to the database or sending it to the browser screen.
The first parameter is the name of the filter to hook widget_text while the second is the name of the function to executed when the filter is applied execute_php. The third is the priority. It should be always 100.
Line 2 : It executes the function by noting the argument, the HTML generated by the text widget.
Line 3 : Looking for <?php substring inside the HTML. It means there is php to be executed inside the widget.
Line 4 : ob_start() turns output buffering on. While output buffering is active no output i sent from the script, instead the output is stored in the internal buffer. It means the HTML produced by the text widget is temporarily stored into an internal buffer.
Line 5 : This is the final step to get the output. At this time we need to evaluate the HTML as if it was a php script. eval function does this job.
Line 6 and 7 : Once the php has been processed, we need to save output buffer content, clean the output buffer and turn off output buffering.
Finally at Line 9 the HTML is returned, with the php correctly parsed.
Isn’t it cool to have php executed without needing any plugin? I think so. Drop off your comments below.