How to Plonk a Widget into a Page Using a Shortcode

This article was written on the site “digging into WordPress” it is here on a temporary basis to check it for sanity.
It was written in 2010 but now it is 2015 it may no longer be valid.

Call a Widget with a Shortcode
Posted by Chris Coyier on April 12th, 2010
Call a Widget with a Shortcode
We covered how to run a shortcode in a widget. But what about inserting a widget with a shortcode? I recently had this situation come up. I had a single page where I just wanted to be able to chuck in a widget without the whole rigmarole of creating a special widgetized area and probably a custom page template for that widgetized area and such. I wanted to just put [widget widget_name=”my_widget”] in the pages content and have that widget pop in. Turns out it wasn’t as easy I wanted it to be, but it’s not that bad…

The answer was creating a custom function for the functions.php file which would output any widget by name. There is a function just for that: the_widget() (incomplete codex page).

The logic

Test if widget exists
If it does…
Start capturing output
Output widget
End capturing output
Return captured output
If it doesn’t exist…
Output fail message
The code for functions.php

function widget($atts) {

global $wp_widget_factory;

extract(shortcode_atts(array(
‘widget_name’ => FALSE
), $atts));

$widget_name = wp_specialchars($widget_name);

if (!is_a($wp_widget_factory->widgets[$widget_name], ‘WP_Widget’)):
$wp_class = ‘WP_Widget_’.ucwords(strtolower($class));

if (!is_a($wp_widget_factory->widgets[$wp_class], ‘WP_Widget’)):
return ‘

‘.sprintf(__(“%s: Widget class not found. Make sure this widget exists and the class name is correct”),’‘.$class.’‘).’

‘;
else:
$class = $wp_class;
endif;
endif;

ob_start();
the_widget($widget_name, $instance, array(‘widget_id’=>’arbitrary-instance-‘.$id,
‘before_widget’ => ”,
‘after_widget’ => ”,
‘before_title’ => ”,
‘after_title’ => ”
));
$output = ob_get_contents();
ob_end_clean();
return $output;

}
add_shortcode(‘widget’,’widget’);
Usage

Now in Post/Page content, you can use the widget just by referencing it by name:

[widget widget_name=”Your_Custom_Widget”]

Leave a Reply

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