Get FAST WordPress Support
WordPress Shortcodes In Sidebar And Php

WordPress Shortcodes in Sidebar and PHP

It is a shame that when using WordPress Shortcodes in Sidebar WordPress doesn’t support shortcodes in sidebars by default, but it’s easy to fix. I’m going to focus on a specific use of shortcodes in a sidebar, but you could use this technique for any shortcode. Shortcodes are a flexible way to allow WordPress users to place the output of a plugin wherever they want in a post or page.

When someone installs the plugin they can add the shortcode, [my-plugin] in this case, to a post or a page. They will see the plugin output inserted at the spot of the shortcode in place of the moniker. Nice and tidy, one of the best features of WordPress. However, if you get a little creative and decide to add the shortcode to a text widget (wp-andy, Appearance, Widgets) you see, well, the shortcode text. This can be very frustrating. You understand the concept and put the code where you want to see the output and — nothing.
If you are having this problem there is a line of code you can add to your system that will allow shortcodes to render within a text widget.

Here’s the code:

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

The second line is the one that makes the shortcodes work, but you’ll want to include both. WordPress will apply the autop filter — the one that turns your line breaks into paragraph and break tags. The first line prevents that from happening.

But if sometimes you like to use a Shortcode in your Template or just don’t like to put it in the Editor, for example you like to insert it in the Custom Field or somewhere else. There is a function in WordPress which helps you to insert a shortcode somewhere else besides your Editor.

The easiest method is to access a shortcode, for example myshortcode; with the help of do_shortcode(). I will show you a code example; you put it into your Template – for example in the single.php of your Themes.

echo do_shortcode('[myshortcode]');

If you work with parameters, then the Shortcode can process these prarameters and they can be delivered.

echo do_shortcode('[myshortcode param="blahblahblah"]');

Please Note: PHP differentiate ‘ and “, this can become a problem for a beginner. For example the following code wouldn’t work:

echo do_shortcode('[myshortcode param='blahblahblah']');

this works

echo do_shortcode('[myshortcode param="blahblahblah"]');

Another example is to use a value from the Custom Field example-name and deliver it to the Shortcode example_shortcode for the parameter product.

$example_product = get_post_meta( $post->ID,'example-name', $single =true);if($example_product)
	echo do_shortcode('[example_shortcode product="'. $example_product .'"]');?>

We hope this was helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *