Posted by & filed under WordPress.

I needed to retire a WordPress widget to a group of sites in my WordPress network, and I wanted to do this programmatically since it would have taken a considerable amount of time to do this manually to each individual site within my WordPress network. Here is how I did this…

I needed to retire a WordPress widget to a group of sites in my WordPress network, and I wanted to do this programmatically since it would have taken a considerable amount of time to do this manually to each individual site within my WordPress network.

The main trick to doing this is understanding that WordPress assigns a unique numerical ID to each widget instance, so not only does the sidebar item need to be registered with this unique ID in the “sidebars_widgets” key/value pair in the wp_options table (or wp_[blog_id]_options table if you are running a multisite WordPress network as I am), but you also need to provide the settings for this widget instance within the “widget_[widget_name]” key/value pair, even if there are no settings for this widget. My widget didn’t support any settings, so I simply had to provide an empty array assigned to a key representing this unique ID to be serialized.

The following is the code I used, where $row->blog_id is my blog’s ID in my WordPress network, and “mywidget” is my widget name. Some adjustments will be needed here for individual WordPress site installs, but hopefully this code snippet is clear enough to get the gist of how to approach this task!

$widgetmeta = get_blog_option($row->blog_id, 'widget_mywidget');
$nextidx = 0;
foreach ($widgetmeta as $key=>$val) {
	if (is_array($val) && $key !== "_multiwidget" && $key > $nextidx) {
		$nextidx = $key;
	}
}
$nextidx++;

$widgetdata = get_blog_option($row->blog_id, 'sidebars_widgets');
foreach ($widgetdata as $sidebar=>$sidebardata) {
	if ($sidebar == "wp_inactive_widgets") {
		//$widgetdata['wp_inactive_widgets'] = array();
		continue;
	}
	if (is_array($sidebardata)) {
		foreach ($sidebardata as $sidebaridx=>$sidebaritem) {
			if (preg_match('/^dbv_widget-/', $sidebaritem)) {
				$widgetdata[$sidebar][$sidebaridx] = preg_replace('/^myoldwidget-[0-9]+/', 'mywidget-' . $nextidx, $sidebaritem);
				$widgetmeta[$nextidx] = array();
				$nextidx++;
			}
		}	
	}
}
update_blog_option($row->blog_id, 'widget_mywidget', $widgetmeta);
update_blog_option($row->blog_id, 'sidebars_widgets', $widgetdata);