Call dynamic_sidebar but include/exclude named widgets?

dynamic_sidebar() calls wp_get_sidebars_widgets() to get all widgets per sidebar. I think filtering this output is the best way to remove a widget from an sidebar.

add_filter( 'sidebars_widgets', 'wpse17681_sidebars_widgets' );
function wpse17681_sidebars_widgets( $sidebars_widgets )
{
    if ( is_page() /* Or whatever */ ) {
        foreach ( $sidebars_widgets as $sidebar_id => &$widgets ) {
            if ( 'my_sidebar' != $sidebar_id ) {
                continue;
            }
            foreach ( $widgets as $idx => $widget_id ) {
                // There might be a better way to check the widget name
                if ( 0 === strncmp( $widget_id, 'links-', 6 ) ) {
                    unset( $widgets[$idx] );
                }
            }
        }
    }

    return $sidebars_widgets;
}

Leave a Comment