| |

Include a Sidebar with a Shortcode in WordPress

Recently I was faced with a pretty interesting problem where I wanted to have a page that was structured: Content – Widgets – Content. Instead of hacking together some sort of Content – Sidebar – Metadata on the backend, I decided to make sidebar widgets accessible via a shortcode you can use in the WordPress editor. You can download the code on Github here.

The crux of the matter is three function focused around the output buffer: ob_start(), ob_get_contents(), and ob_end_clean(). ob_start() will tell PHP to place any following output into a buffer that you can access via ob_get_contents(). So for example, in this code:

ob_start();
 print "Hello World!";
 $text= ob_get_contents();

The value of $text would be Hello World. You would end the output buffer with ob_end_clean(). With that in mind, let’s look at the shortcode!

If you need a primer on WordPress shortcodes, you can start with the WordPress Codex’s entry (you can also pick up either of my WordPress books, wink wink nudge nudge). Our shortcode will look like this: [get_sidebar]. It can also accept one argument for name (really slug) of the sidebar. So if you have a sidebar named “home” you can do [get_sidebar name=home]. Here’s our function:

function sidebar_shortcode($atts, $content="null"){
  extract(shortcode_atts(array('name' => ''), $atts));

  ob_start();
  get_sidebar($name);
  $sidebar= ob_get_contents();
  ob_end_clean();

  return $sidebar;
}

By default, the argument $name will be set to blank, so the default sidebar would be called. Notice out ob_ functions; after ob_start(), we call get_sidebar(), which means the entire output from that function will be put on the buffer, which we then throw into the $sidebar variable and return. It’s very important to called ob_end_clean()! If you don’t, the sky will fall on your head.

The last step is to register the short code:

add_shortcode('get_sidebar', 'sidebar_shortcode');

And that’s it! You’re done. It’s worth nothing that you should prefix both your function and your shortcode to avoid conflicts. Again, you can download the code from Github.

One Comment

Leave a Reply

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