Is it possible to include or exclude specific named widgets that are assigned to a named dynamic_sidebar call?

For example, if I’ve registered a sidebar named “my_sidebar” and the user had placed a “Links” widget into it, I want to be able to include or exclude it based on a custom setting in my theme options panel.

Is this possible?

Any insights much appreciated.

3 s
3

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 Reply

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