If you’re in the business of building themes for fun, for clients, or for purchase within a marketplace or your own store, then there’s a chance that there’s some type of functionality that’s unique to your theme that should be activated whenever the theme is activated.
In my experience, this is something that’s typically unique to niché WordPress themes because they tend to have specific features, customizations, and so on that are relevant to their theme.
Case in point: Let’s say that you’re working on a niché theme that has a number of widgetized areas, but also has very specific widgets for said areas. That is, upon theme activation, you want to make sure that each widgetized area is clear so not to bust up the layout.
In other words, you need to programmatically deactivate WordPress widgets whenever the theme is activated so that the layout of the theme looks as it should when the user activates it.
How To Deactivate WordPress Widgets Programmatically
There are a number of good articles that provide ways to unregister a widget in WordPress (such as this Codex article), but there’s a different in unregistering a widget and deactivating a widget:
Unregistering a widget completely removes it as an option to drop into a widgetized area; deactivating a widget removes all activate widgets from the sidebars but still makes them available for use.
Deactivating widgets is actually really simple (especially if you’re looking to do it on theme activation):
Here’s what’s happening in the code above:
- First, check to see if the `acme_cleared_widget` flag exists and is set to `true`. If not, then we need to update the options; if so, then we won’t do anything.
- If the flag has not been set, then we’ll set the `sidebars_widgets` option equal to an array and then set the `acme_cleared_widget` value to `true`.
Easy enough, right?
Simply put, the activate widgets are kept in a serialized array in the
sidebars_widgets option in the options table. By serializing an empty array, we’re completely removing whatever was stored before (more on this at the end of the post).
The reason that this is wrapped in a conditional and has the
acme_cleared_widgets option is so that we’re not clearing widgets every single time the
after_setup_theme action is fired. Instead, we’re only looking to clear the widgets one time.
Also, since this is a destructive action, a case can be made that this should be triggered by the user’s taking some type of action in the dashboard and that it should require confirmation, but that’s outside the scope of what’s being shared.
Regardless, the point is that there’s a difference between unregistering widgets and deactivating widgets, and this is how you can programmatically deactivate WordPress widgets.