3

I want to cleanup all inactive widgets. I tried following snippet as suggested by this answer Script to remove all inactive widgets?.

$sidebars_widgets = get_option( 'sidebars_widgets' );
$sidebars_widgets['wp_inactive_widgets'] = array();
update_option( 'sidebars_widgets', $sidebars_widgets );

I also tried deleting option sidebars_widgets directly from the options table.

But after page is refreshed, old value is restored with all inactive widgets. How can I remove all those inactive widgets at once? Thanks in advance.

2 Answers 2

2

You should do it with after_setup_theme action:

function remove_inactive_widgets() {
     $sidebars_widgets = get_option( 'sidebars_widgets' );
     $sidebars_widgets['wp_inactive_widgets'] = array();
     update_option( 'sidebars_widgets', $sidebars_widgets );
}
add_action( 'after_setup_theme', 'remove_inactive_widgets' );
3
  • I tried above code. It removes inactive widgets but also blocks to add new widgets. I just want to clear up existing inactive widgets and I am trying to remove from plugin rather than theme. Commented Apr 21, 2015 at 3:49
  • I've checked its working in theme and inside plugin, please test it on fresh wp or deactivate other plugins.
    – Behzad
    Commented Apr 21, 2015 at 17:52
  • I deactivate all other plugins tried with above code only as a plugin. Now inactive widgets are hidden but no more any widget can be added in Inactive Widgets. Any idea? Commented Apr 22, 2015 at 3:56
1

Widget customizations are saved in the widget itself. So in addition to deleting the sidebars_widgets, you have to delete the custom data in the widget as well.

$sidebars_widgets = get_option('sidebars_widgets');
foreach ($sidebars_widgets as $key => $value) {
    foreach ($value as $widget_id) {
        $pieces = explode('-', $widget_id);
        $multi_number = array_pop($pieces);
        $id_base = implode('-', $pieces);
        $widget = get_option('widget_' . $id_base);

        //Here it deletes the widget customizations that are linked to an id
        unset($widget[$multi_number]);

        update_option('widget_' . $id_base, $widget);
    }

    //Here it erases all the page's widget. Set ampty array.
    $sidebars_widgets[$key] = array();
}
update_option('sidebars_widgets', $sidebars_widgets);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.