The new reader centric version of my website launched last night. When I was setting up the new home and about page views, I needed to hide a widget. Normally there is a brief “about me” widget on most pages. This widget allows visitors who came directly to a page or article to learn more about me. Since the about page and homepage have their own dedicated areas for this information, I wanted to hide the “about” widget.
WordPress has a filter for retrieving the sidebars_widget called sidebars_widgets
. Using this filter we can create our own callback function to get the sidebars widgets that are available. Our callback function will take one argument called $sidebars_widgets
.
add_filter( 'sidebars_widgets', 'remove_about_me_widget' );
function remove_about_me_widget( $sidebars_widgets ) {
// TODO
}
First thing we need to check for is that we are not in the admin panel. If in the admin panel, return the sidebars_widgets back unedited. We will then check if we are on the home or about page.
if( is_admin() ) {
return $sidebars_widgets;
}
if( is_page('about') || is_home() ) {
// REMOVE THE WIDGET
}
We need to find what key our widget is in using the sidebar ID as the key. For example; I assigned the sidebar on the right side of my site the ID of primary-sidebar. We will use array_search
to find the place of the widget. We are targeting the ID of the widget (in my case the ID is text-3). If the key is found, we will remove it from the array.
$key = array_search('text-3', $sidebars_widgets['primary-sidebar']);
if($key !== false) {
unset($sidebars_widgets['primary-sidebar'][$key]);
}
That’s it! Our widget should no longer be showing on the about or homepage. Here is how our finalized code should look:
add_filter( 'sidebars_widgets', 'remove_about_me_widget' );
function remove_about_me_widget( $sidebars_widgets ) {
if( is_admin() ) {
return $sidebars_widgets;
}
if( is_page('about') || is_home() ) {
$key = array_search('text-3', $sidebars_widgets['primary-sidebar']);
if($key !== false) {
unset($sidebars_widgets['primary-sidebar'][$key]);
}
}
return $sidebars_widgets;
}