If you are using the default WordPress installation (meaning you haven’t modified any of the code or added any plugins, WordPress only allows you to insert shortcodes into the post/page content area. Remember that shortcodes are simple codes that are “placeholders” for larger and/or more complex blocks of code or function. Shortcodes normally look like this:
But what if you want to use shortcodes in other areas of your site? I’m sure you could go find a plugin to add to your site because there is most definitely “a plugin for that”. But rather than adding the overhead that comes with a full blown plugin. You can accomplish the same thing with just a few lines of code. So lets take a look at the code you would use.
Adding Shortcode to Text Widgets
Lets first take a look at the code that needs to go into your active theme’s functions.php file.
add_filter( 'widget_text', 'shortcode_unautop' ); add_filter( 'widget_text', 'do_shortcode' );
The second line, the one that says do_shortcode is the line that actually makes a shortcode work in the text widget area. The first line deals with any problems that might arise if you check the “add paragraphs automatically” to the text widget. This first line of code will prevent the automatic insertion of the paragraph tag. Hence un – auto – p (Now you see it right….)
Adding Shortcodes to a WordPress Template File
When we are working in PHP we can extend the code we just used in the text widget section (do_shortcode) and utilize in a PHP file. We just need to tell PHP which shortcode we want to use. Here’s the example:
<?php do_shortcode('[shortcodename]'); ?>
This post continues for members of WebDesign.com. WebDesign.com members receive additional instruction and code snippets for using shortcodes in the comments area, excerpt fields of posts, in the user descriptions, and in all the taxonomy description areas (category, tags, more). To learn more about WebDesign.com membership and the many benefits to developers, visit WebDesign.com