Sometime we need to disable sidebar / widget area conditionally, The most popular option is to use Widget Logic Plugin, or you can try my plugin: Atomic Widget (update: no longer available). But if you prefer manual way, maybe for client site where you don’t want to confuse them with extra settings in widget you can do this easily with this code.
add_filter( 'sidebars_widgets', 'my_disable_sidebar
' );
function my_disable_sidebar( $sidebars_widgets ) {
if ( is_home() )
$sidebars_widgets['footer'] = false;
return $sidebars_widgets;
}
You can read more explanation on the code in Justin Tadlock post: Disable widget areas (sidebars) without touching theme templates.
But how if you want to disable only specific widget?
sidebar_widgets
is an array of sidebar, but it’s multi dimentional array, with the list of widget in widget area/sidebar. The code you can use to disable widget:
add_filter( 'sidebars_widgets', 'my_disable_widget' ); function my_disable_widget( $sidebars_widgets ) { /* disable it only singular pages */ if ( is_singular() ){ /* get each sidebar / widget area */ foreach( $sidebars_widgets as $widget_area => $widget_list ){ /* get all widget list in the area */ foreach( $widget_list as $pos => $widget_id ){ /* widget with id "meta-3" */ if ( $widget_id == 'meta-3'){ /* remove it */ unset( $sidebars_widgets[$widget_area][$pos] ); } } } } return $sidebars_widgets; }
very easy right? using unset
in this filter will remove the widget from the list, so if you use widget conditional is_active_sidebar( 'your-sidebar-name' )
in your theme, it will work correctly.
Thanks alot for this really helpful tutorial, but there is one thing i want to ask, from where will i get the “widget id” which i want to remove from the sidebar?
add_action(‘in_widget_form’, ‘spice_get_widget_id’);
function spice_get_widget_id($widget_instance) {
if ($widget_instance->number==”__i__”){
echo ‘Widget ID is: Pls save the widget first!’;
} else {
echo ‘Widget ID is: ‘ . $widget_instance->id . ”;
}
}
Widget ID will bу in Admin panel