Shortcode in custom sidebar widget

I keep saying that WordPress makes a great CMS because of it’s ease of use and great flexibility, especially with all the great plugins that are available for it. However the disadvantage of using too many plugins is that, as you start to extend WordPress, you reduce the simplicity of it.

It is because of this that I’ve started to write custom functions that are embedded into the themes that I create. One of the plugins I replaced was a sidebar text widget that I used for creating custom sidebar text on a per post basis.
The only problem with it was that it created a link within the Custom Fields section which didn’t work as expected so you’d have to scroll down to the bottom of the editor and add it in. Confusing, it was!

Instead I created my own Custom Fields, disabling the WordPress defaults, based largely on the work of Steve Taylor.

Two of the fields are designed for custom sidebar text so the next process was to register widgets however because they need to get data from a post or page I needed to tell the widget what the post ID is.

After a lot of Googling and even more trial and error I realised that the only way I was going to get the ID into the function was to make it a global which worked beautifully…

function sidebar1() {
 echo '<div id="SidebarText1">';
 echo get_post_meta($GLOBALS['current_id'], '_sejaWP_sidebar_text_1', true);
 echo '</div>';
}
register_sidebar_widget(__('Side Text 1'), 'sidebar1');

Until I needed to add some shortcode to make a custom menu work

Googling shortcode in widgets returns a whole lot of posts that tell you to place the following code in the functions.php file

add_filter('widget_text', 'do_shortcode');

But this simply wasn’t working for me, probably because of the Globals variable call but thankfully one of the many articles led me to Stephanie Leary’s article Using Shortcodes Everywhere which introduced me to other possibilities.

The updated widget now uses do_shortcode which is designed for use directly within a theme (which I guess in a way it is!)

function sidebar1() {
 echo '<div id="SidebarText1">';
 echo do_shortcode(get_post_meta($GLOBALS['current_id'], '_sejaWP_sidebar_text_1', true));
 echo '</div>';
}
register_sidebar_widget(__('Side Text 1'), 'sidebar1');
This entry was posted in Technical. Bookmark the permalink.

Leave a Reply

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