Widgets Gone Wild

Today’s tip is quick (and easy!). We’re going to learn how to extend your WordPress widgets without plugins. In 5 minutes or less you’ll know how to:

  1. Use shortcodes in widgets without a plugin
  2. Execute PHP code in widgets without a plugin.

Don’t believe me? Just try it! All you’ll need is your theme’s function.php file and a party hat.

Use Shortcodes in Widgets Without a Plugin

Ever needed to use a shortcode in a widget area, but couldn’t get it to work? Here’s why: by default, WordPress doesn’t support it. But don’t cry! You can add this short snippet to your theme’s function.php file and you’ll be abusing shortcodes in widgets in no time!

// Enable shortcodes in widgets
add_filter('widget_text', 'do_shortcode');

Use PHP in Widgets Without a Plugin

Sometimes you might want to execute some php in a widget. You can download plugins to do the job or you can do it yourself with just a handful of code. Add this to your theme’s function.php file:

// Enable PHP in widgets
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;
}

Done? Now you can pop PHP into a sidebar widget and it’ll work like a charm! If you’d like to know why the code works, I invite you to read this explanation by Emanuele Feronato.

That’s It!

Are there other things you’d like to do with widgets without the use of a plugin? Leave a comment below and let’s discuss!

 

Comments

  1. says

    This is great! The only problem I’m running into is the shortcode snippet messes up the rest of my widgets by causing them to align horizontally rather than vertically. It also changes the size of my widget titles. Any suggestions how I can fix this?

  2. Darryl says

    Is it possible to include a php function within a shortcode? I can’t seem to get that to work.

  3. says

    Thanks for this great tutorial. Do you have a tutorial on displaying list of posts in one post with shortcodes. I found many plugins for that, but I want to do it manually instead.

  4. says

    Hi,This is great.
    I have a doubt..I install a plugin on my site , and it contain a short code like [wpgc id="1"].So for getting result i need to past this short code on corresponding post.It is working perfectly..Now i need to convert this short code to php code .so i create a new page in that plugin folder namely camp.php & it contain

    but when i run that page then “Call to undefined function do_shortcode()” error msg.
    any idea?