How to Use WordPress Shortcodes in Widgets

I use several plugins on a regular basis that provide shortcodes. If you don’t know what shortcodes are or how they can be used, please read this tutorial first. If you are familiar with shortcodes and want to know how to use them in a Widget, read on.

The Good ‘Ole Days

I tried using shortcodes in Widgets a few years ago and quickly became frustrated because  it wasn’t possible (back then). I always thought of it as “…one of those WordPress quirks…” and never gave it much thought until the other day.

Why I Needed Shortcodes in Text Widgets

I manage a site that makes heavy use of a plugin to create and manage tables. In this installation I am managing well over a hundred separate tables, each containing dozens of rows of data. As it was, these tables were inserted into individual pages using the plugin’s shortcode that passed the table id like this:

[table id=17]

That works perfectly and displays the table and it’s contents beautifully on the page. However, I received a request to put many of these tables into the sidebar area of the site. I thought I was in for a LOT of work. Knowing (or so I thought) that I couldn’t use these table shortcodes in a Text Widget I thought I would have to manually code the contents of over 75 Text Widgets. Gulp!

Never Assume You Know it All

Knowing that the WordPress core had been updated several times since I tried using shortcodes in Widgets and that new features had been added, and knowing that there are many WordPress developers out there smarter than me (or is that I?)…I did a quick Google search and low and behold, the answer was not far away.

You can force your Widgets to accept shortcodes by putting one line in your theme’s functions.php file.

add_filter( 'widget_text', 'do_shortcode');

I read a bit more and followed another link and found out that using two lines is a bit better.

add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');

Why the additional line? From Stephanie Leary of

The second line is the one that makes the shortcodes work, but you’ll want to include both. If you check “add paragraphs automatically” on the widget, WordPress will apply the autop filter — the one that turns your line breaks into paragraph and break tags. If a shortcode is on its own line, it would normally get wrapped in a paragraph tag. The first line prevents that from happening.

It was as easy as that. I added those two lines in my theme’s functions.php file, dropped some table shortcodes in my Text Widgets, and there were my tables in the sidebar just as had been requested. Thank you WordPress dev team, Google, and Stephanie Leary!

I also learned of a few ways to create your own shortcodes, and the best part is that you don’t have to be a plugin developer to do it. Stay tuned for that tutorial coming soon. In the meantime, you might want to…