Starting directly on the issue 🙂 ; The below code snippet is for executing PHP code in the WordPress text widget. This snippet goes into ‘functions.php’ of a WordPress theme.
The first thing we are doing is, add_filter() so that we specify from which widget we get the code/ data. Hence,
add_filter( ‘widget_text’, < functionName >, < priority > );
For further read: WordPress add_filter ();
Next, our custom function ‘execute_php’ receives the code keyed-in in the wordpress text widget through the parameter ‘$html’. Then looking for ‘ < ? php ', if true, start output buffering till ' ? > ‘. Further, gets the content in between assigned to $html and closing off the output buffering. Finally, returning the output i.e. ‘$html’.
What to do?
Login to your WordPress admin section and fly to Appearance -> Widgets. Then drag drop a ‘Text widget’ to a sidebar and key-in your php code directly, if the code is of small else, write your code in a PHP file and then use ‘include()’ or ‘include_once()’ (Note: ‘require()’ or ‘require_once()’ will not work here.). For e.g: if you want to include a php file, we need to write “< ? php include (' yourPHPfile.php ' ); ? >“, without the spaces in the PHP open and closing tags. That’s all, you code will work smoothly.
This is useful for executing small and quick php task for which we don’t want to write whole widget code. But this system is suggested to those who know about PHP and WordPress, at least basic. Because, even if someone accidentally deletes a part of code, you know how to get back the code to work. And Warning No.2: this is just a shortcut for lazy people like me :roll and not recommended for a good WordPress theme.
And as usual, Thanks for reading.