You can use wp_get_sidebars_widgets()
with an “on demand” filter callback. This means we’re adding the filter callback, right before the call to the function and then remove right inside the callback again. This allows us, to use it only once. It also means, that we need to set it right before the call to wp_get_sidebars_widgets()
every time we need only the specified widget.
If you need different widgets on different pages, just add a switch/foreach
inside the callback and use conditional tags like is_home()
, etc.
// For your functions.php
/**
* Call a specific sidebar widget
* Filter callback
*
* @param array $sidebars_widgets
* @return mixed bool/object $sidebars_widgets The widget or FALSE if not found
*/
function filter_sidebars_widgets( $sidebars_widgets )
{
// SET your wanted widget right here:
$wanted = 'recent-posts-2';
// Prevent intercepting another call - on demand filter(!)
remove_filter( current_filter(), __FUNCTION__ );
if ( is_array( $sidebars_widgets ) )
{
// array_search() returns FALSE in case the widget isn't present
$index = array_search( $wanted, $sidebars_widgets, FALSE );
$sidebars_widgets = $sidebars_widgets[ $index ];
}
else
{
// we add a manual FALSE in case the widget isn't present
$sidebars_widgets = $wanted === $sidebars_widgets ? $sidebars_widgets : FALSE;
}
return $sidebars_widgets;
}
// In your template: First add the filter...
add_filter( 'sidebars_widgets', 'filter_sidebars_widgets' );
// ...then call the function.
$widget = wp_get_sidebars_widgets();
// Now do something with $widget :)
// As we removed the filter inside the callback, any other call
// to wp_get_sidebars_widgets(); will behave like normal.