Like the blog? Get the book »

Shortcodes in Widgets

Shortcodes in Widgets

I had occasion the other day to run a shortcode inside of a text widget. You know shortcodes… we talk about them all the time. They are keywords in [square_brackets] that do something special.

Sometimes they do something really simple like return a string (so you can have a global location to customize some string of text, for example), or they do something more complicated like call a plugin that does something fancy like build a photo gallery.

But alas…

Screenshot showing an example shortcode added to the Text widgetThis ain’t gonna work “out-of-the-box”

After tinkering with some far-too-complicated solutions, someone on Twitter helped me with a deliciously simple solution: Just add this to your theme’s functions.php file:

add_filter('widget_text', 'do_shortcode');

This will ensure that the text content of widgets is parsed for shortcodes and those shortcodes are ran. Awesome.

Stephanie Leary wrote a great article on Using Shortcodes Everywhere, which covers this as well as using shortcodes in a bunch of other places: Comments, templates, excerpts, etc.

5 responses

  1. I use this for Members only content. I use a [member][/member] code for content that is only for members and sometimes along side use a [visitor] code too.

  2. One line solutions are my favorite kind of solutions.

  3. Wow, if I had known this while doing my last WordPress project, it would have made my life so much easier. Unfortunately for deadline restrictions, I didn’t have time to thoroughly research it.

    Thanks for sharing!

  4. This makes my life a lot easier. I wonder why WordPress would filter out shortcodes for use in widgets.

  5. Thank you, thank you, THANK YOU! You saved me hours of work with this. Seriously. Much appreciated!

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace