WordPress shortcodes are small, one word keywords enclosed in [square brackets] that allow you to add functionality to WordPress. By default, you can use shortcodes in Posts and Pages, but not Widgets. Some users may want use a Widget that uses a shortcode to add a gallery or other macro into the sidebar. For more information on using Widgets, please see our WordPress Education Channel: Introduction to Plugins and Widgets.
How WordPress Handles Shortcodes in Widgets by Default
First, we'll see the default WordPress behavior when we use the gallery shortcode in a Text Widget.
- Log into the WordPress Dashboard.
- Click on Appearance > Widgets
- Drag a Text Widget Into the Sidebar (on the right side of the page)
- Give the Widget a Title and type this shortcode into the text area of the Widget:[gallery]
- Save and close the Widget
Here's what we see by default:
Well, that's not very exciting is it? The good news is that this is fairly easy to fix. You actually have two choices to enable shortcodes in widgets in WordPress:
- Use the Shortcodes in Sidebar Widgets plugin for WordPress
- Edit the functions.php file for your theme.
Using the Shortcodes in Sidebar Widgets plugin in WordPress
Installing and enabling this plugin is the preferred method for adding this capability in WordPress. With this plugin, even if you change your theme in the future, shortcodes in your WordPress sidebar will still be enabled.
- Since we're already in the WordPress dashboard, search for and install the Shortcodes in Sidebar Widgets plugin.
- Make sure you have enabled the Shortcodes in Sidebar Widgets plugin.
- Refresh the page with the sidebar in your WordPress site and you will now see that the shortcode is working:
Editing Your Theme's functions.php file
While the following method is not the recommended method, some people may want to know how to enable shortcodes in widgets by adding some code to their theme's functions.php.
The following method would need to be repeated for each theme if you decide to switch themes in the future. Before proceeding with the following instructions, you should first create a Child Theme for your preferred theme and activate the Child Theme.
- Using the cPanel File Manager, create a new file named functions.php inside your Child Theme directory:
- Open this file for editing by selecting either Edit or Code Editor in the cPanel File Manager.
- If a notification appears regarding encoding, make sure utf-8 is selected and click the Edit button in that window.
- Input the following code in the functions.php file:
add_filter( 'widget_text', 'shortcode_unautop');
- Click the Save Changes button to save your changes, then click the Close button to close the file.
- Now shortcodes are enabled in Text Widgets for your WordPress site: