Limit the number of inactive widgets

Tested under v3.2.1:

$sidebars = wp_get_sidebars_widgets();
if(count($sidebars['wp_inactive_widgets']) > 10){
    $new_inactive = array_slice($sidebars['wp_inactive_widgets'],-10,10);

    // remove the dead widget options
    $dead_inactive = array_slice($sidebars['wp_inactive_widgets'],0,count($sidebars['wp_inactive_widgets'])-10);
    foreach($dead_inactive as $dead){
        $pos = strpos($dead,'-');
        $widget_name = substr($dead,0,$pos);
        $widget_number = substr($dead,$pos+1);
        $option = get_option('widget_'.$widget_name);
        unset($option[$widget_number]);
        update_option('widget_'.$widget_name,$option);
    }

    // save our new widget setup
    $sidebars['wp_inactive_widgets'] = $new_inactive;
    wp_set_sidebars_widgets($sidebars);
}

The above code limits the inactive sidebar to the last 10 widgets, and only the inactive sidebar. It also removes the options for the widgets that have been deleted.

Leave a Comment