How to Use a WordPress Shortcode Outside the Post Editor
Shortcodes in WordPress are amazing. They are essentially macros that allow you to place content anywhere on your site.
For example, instead of inserting a whole bunch of images to create a gallery, you simply use the shortcode [ gallery ]. WordPress offers a few shortcodes by default and there are hundreds to choose from via available plugins.
There are a couple of places you may want to use shortcodes outside of your post content. Sidebar widgets for one, and perhaps somewhere inside your theme (in the footer, for example). In this post we’ll take a look at how you can make this happen.
Enable Shortcodes in Widgets
Some widgets you use via plugins may support the insertion of shortcode, however the default text widget does not. To make sure shortcodes are indeed applied properly you can use a single line of code, pasted into your theme’s
If you are using a third-party theme (any theme you didn’t make yourself), you really should use a child theme, take a look at our guide to child themes on how to make it happen. You can, of course, also create your own plugin.
Using Shortcodes in Theme Files
If you would like to output a shortcode in theme files, you can do that pretty easily as well.
All you need is the
do_shortcode() function, which should be wrapped around the shortcode itself. Here’s an example:
Now why would you do this if it is hard-coded into a theme? In many cases theme authors prefer to go with a shortcode if they are hard-coding some functionality, which will be filled up using theme options but uses elements contained in a shortcode.
Let’s presume that the theme author provides a shortcode for a special gallery, which you can create using
[specialgallery id='44,124,342'] where the IDs are images to display. If the theme uses this gallery type in the header on the home page, the theme could provide the options to select the images on an options page, then it could be output using this shortcode.
The benefit here is standardization. All galleries which look the same are the same, meaning they can be modified together.Tags: