Blog

Hide and show widgets programmatically

WordPress

To hide a specific widget on certain pages or under specific conditions, you can rely on a plugin like Widget Logic or Widget Options. Alternatively, you can achieve the same result with a few lines of code:

add_filter('sidebars_widgets', 'pure_conditionally_remove_widget');

function pure_conditionally_remove_widget($sidebars_widgets)
{
	if (is_admin()) {
		return $sidebars_widgets;
	}

	if (!is_front_page() && !is_archive()) {
		foreach ($sidebars_widgets as $widget_area => $widget_list) {
			foreach ($widget_list as $pos => $widget_id) {
				if ($widget_id == 'text-3') {
					unset($sidebars_widgets[$widget_area][$pos]);
				}
			}
		}
	}

	return $sidebars_widgets;
}

In the above example, the widget with the ID text-3 is removed from the front page. The widget ID corresponds to the CSS ID of the widget in the frontend. You need to adjust the ID and condition to suit your specific needs.