Allowing WordPress Short Codes To ‘run’ in the sidebar

Allowing WordPress Short Codes To ‘run’ in the sidebar

WordPress “shortcodes” are wonderful things…. they are a way to create functions (or macros) within your wordpress theme for any number of things.  I use Shortcodes a lot when creating sites for my clients – and it makes things a lot easier.

Essentially a shortcode is text with your content that is ‘wrapped’ in square brackets (eg. [yourshortcode]).  More complex shortcodes allow for content to be included between the text to display on the site, e.g:
[yourshortcode]
Some text goes here
[/yourshortcode]

The wordpress code framework allows wordpress to ‘listen’ for text between square brackets, and if a matching code exists within the theme or plugins, then run the function associated with the code rather than display the text.

This article isn’t about how to write a shortcode though…  By default, WordPress will ‘execute’ shortcodes within the main content of a page and not the sidebars.  This doesn’t mean that the shortcode can work in the sidebar… you just need to add one line to your themes functions.php file to make it happen.

To get shortcodes to work in your sidebar, edit the active themes functions.php file:

add_filter('widget_text', 'do_shortcode');

That’s it really….

Now…. some plugins will provide functionality that looks like shortcodes – but it isn’t really.  If you have added the above line to your theme but the shortcode isn’t displaying as you would expect, test it using the code below:

function helloworld() {
$content1.='Hello World';
return $content1;
}
add_shortcode ('sayhello','helloworld');

In a text widget in your sidebar put:

[sayhello]

and when you display the sidebar, the words Hello World will be displayed.

 

Powered by WishList Member - Membership Site Software