Hide Widgets on Specific WordPress Pages

Chris Blackwell
2 min readApr 27, 2017

--

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;
}

Originally published at Chris Blackwell’s Domain.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chris Blackwell
Chris Blackwell

Written by Chris Blackwell

Programmer and Business owner from Canada / USA. I help businesses and entrepreneurs develop amazing digital products 🚀

Responses (1)

Write a response