Insert Widget with Shortcode in WordPress

Themes are designed very differently from each other. I found myself sometimes use columns template provided by some themes to achieve sidebar like layout. As it is something like 75/25 column split, not standard widget area, inserting a widget needs bit extra work.

This actually becomes a question of how to insert widget anywhere in WordPress. The best solution for me is always using shortcode.

For example, I want to output the Search widget.Ā  Start by outputting the widget, WordPress has a built-in function called the_widget(), which does just what I want, display an arbitrary widget outside of a sidebar. But there is a catch, the function straightly output content like using echo, and doesn’t return a value.

As for writing shortcode, the principle is it must return a string, can not use echo. To resolve this, I use PHP output buffering. Here is the code:

// Custom shortcode to output Search widget anywhere
// Shortcode: [widget_search]
function mycustom_widget_search() {
    ob_start();
    the_widget( 'WP_Widget_Search' );
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

add_shortcode('widget_search','mycustom_widget_search');

ob_start() is the switch to turn output buffering on. While output buffering is active, no output is sent from the script but stored in an internal buffer. The contents of can be copied into a string value using ob_get_contents(). After finish, we need to use ob_end_clean() to discard the buffer contents.

You can insert the code snippet into the theme function.php. For me, I always add my custom work in a custom plugin. This will not be effected by any theme update in the future.

To use the shortcode, I just simply insert [widget_search] in the place I want to display the Search box. To retrieve a different widget, change the name of the widget in line 5. (You can visit the full documentation here.)

[sc:adsense-eoc]