Widgets Gone Wild

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 functions.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', 'shortcode_unautop' );
add_filter('widget_text', 'do_shortcode');

Hat tip to Tim Base for alerting me to some issues with shortcodes in widgets on WordPress 4.8+.

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.

Warning: Use PHP in widgets very judiciously as this is a potential security vulnerability you open by enabling code execution from a widget, versus a file on the server.

Interested in other WordPress Tutorials?

Here are articles specifically for the Genesis Framework and here are general WordPress helper tutorials.

 

12 thoughts on “Widgets Gone Wild”

Comments are closed.

Carrie Dils uses Accessibility Checker to monitor our website's accessibility.