Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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 ) {
            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;
share|improve this answer
Thanks very much. I'm working on this now. Glad to know there's a way to do this. –  Scott B May 19 '11 at 15:23
can you tell me the purpose of the ampersand before the $widgets variable in the foreach? –  Scott B Jun 16 '11 at 16:23
@Scott: The ampersand makes sure we pass a reference to the $widgets array, and not a copy of it that will only exist in the foreach loop. If you leave it out, the unset( $widgets[$idx] ) will remove it from the copy of the array, and $sidebar_widgets will still have the complete array. –  Jan Fabry Jun 17 '11 at 7:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.