+6 votes
in Webmasters by (1.5m points)

How to run PHP code in WordPress text widget

1 Answer

+7 votes
by (725k points)
 
Best answer

Something I've always wondered was how to execute PHP code in the text widgets that WordPress offers us . This can be very useful on certain occasions and can even prevent us from having to resort to some plugin.

image

In my personal case I use it to make calls to an XenForo API and thus obtain the latest articles from my forum, but it is only a use that can be given, there are many other uses, as far as your imagination reaches.

To execute PHP code in text widget there are two options , one is to use a plugin (there are many plugins for this purpose) or the second option to program our own function (it is a very simple function and I will give detailed instructions, so if you want avoid using additional plugins this is a good option).

Execute PHP code in text widget using a plugin

We have a multitude of alternatives, anyway I propose a list with which I have tried and I will leave a brief description and the impression it has given me. The plugins are as follows:

  • PHP Text Widget : the plugin is very simple, it fulfills its mission perfectly. On the WordPress plugin page it says that it is compatible up to version 3.5.2 but I have tried it in version 3.6.1 and it works perfectly.
  • PHP Code Widget : it is another very simple plugin but it has NOT worked for me in my WordPress 3.6.1. On the WordPress plugin page it says it is compatible until version 3.4.2, maybe that's why it didn't work for me.
  • Shortcode Exec PHP : this plugin is more "complete" than the previous options since it gives us extra functionalities. An advantage of this plugin is that it allows you to execute PHP code in comments, RSS, Excerpts and text widgets. It also offers us a "Pro" version of payment, but personally I don't see any point in paying for such a plugin. In my opinion this plugin is too complex for such a simple task that you have to develop.

Execute PHP code in text widget using our own function

The first thing we have to do is open the functions.php file of our WordPress theme and add the following code:


add_filter('widget_text','execute_php',100);
function execute_php($html){
     if(strpos($html,"<"."?php")!==false){
          ob_start();
          eval("?".">".$html);
          $html=ob_get_contents();
          ob_end_clean();
     }
     return $html;
}

And voila, we can add PHP code to our text widgets in the sidebar. It's so simple that I would opt for this solution instead of using a plugin.

I also make a call so that you please use secure PHP code in your widgets to not allow someone with bad intentions to harm your blog.

I hope you liked it and you know that if you have doubts or want to comment something, you have the comments at your disposal.


Most popular questions within the last 20 days

...