How do I add a widget programmatically to a newly created site (WPMU) within a plugin?

Seems the answer was a lot simpler than I thought, so I thought I’d share the answer for those who stumble across this problem too.

Clearly I was missing something in the database that was need, so I too an SQL dump of the database before and after dragging in a widget. Then compared the changes that happened. This helped me analyse what needed to be put in. The result was that I wasn’t putting in my widget settings correctly. Simply put I was adding in

Array
(
    How do I add a widget programmatically to a newly created site (WPMU) within a plugin? => Policies
)

When WordPress was expecting:

Array
(
    [2] => Array
        (
            How do I add a widget programmatically to a newly created site (WPMU) within a plugin? => Policies
            [_multiwidget] => 1
        )
)

So my code looked more like this:

function se160609($blog_id, $user_id, $domain, $path, $site_id, $meta) {
    // Switch the newly created blog.
    switch_to_blog($blog_id);

        // Change to a different theme.
        switch_theme("twentytwelve");

        // Add WordPress options that the widget needs.
        $widget_mywidget = array();
        $widget_mywidget[2]['title'] = "Policies";
        $widget_mywidget[2]['_multiwidget'] = 1;
        update_option( 'widget_mywidget', $widget_mywidget );

        // Add WordPress options to override the default widgets.
        $sidebar_widgets = get_option( 'sidebars_widgets' );
        $sidebar_widgets['sidebar-1'] =  array('mywidget-2');
        update_option( 'sidebars_widgets', $sidebar_widgets );

    // Restore the current blog.
    restore_current_blog();
}
add_action('wpmu_new_blog', 'se160609');

To explain a few bits of information here, notice in the array the first part is [2], this is the instance number of the widget – since widgets can be added in multiple times, so if you wanted to have more than one you could essentially build the array by incrementing from the number 2. It might work by giving it the number 1, but 2 seems to be the best starting number for some reason (its the number that gets assigned first when creating a new multisite site for default widgets, and when you drag and drop).

[_multiwidget] I haven’t fully understood, but I presume it is because I am making a plugin that works on wpmu, so this sets the widget to allow being seen on multisite environments (please correct me if I am wrong).

Leave a Comment