5

I fetched widget id this way:

$the_sidebars = wp_get_sidebars_widgets();
print_r( $the_sidebars['sidebar-1'] );

It shows:

Array ( [0] => recent-posts-2 [1] => recent-comments-2
        [2] => archives-2 [3] => categories-2 [4] => meta-2 ) 

Now I just want to show the recent-posts-2 widget, which means I just want to pass the widget ID recent-posts-2 to the function, and the function will display the widget, such as the following code:

function display_widget($widget_id) {
  ...
  return $wid;
}

When I echo display_widget($widget_id), it will show the widget with HTML, and the class of the default theme.

Do you have any idea?

1

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.