How to add a text widget during theme activation

You’re almost there, except each widget’s settings are stored separately from the sidebars_widgets option, which just stores widget “instances”.

Try out the following function – you’ll still need to use register_sidebar, but it eases the pain for then pre-registering widgets on those sidebars. What it also does is ensure that any existing widgets & their settings aren’t lost in the process.

/**
 * Pre-configure and save a widget, designed for plugin and theme activation.
 * 
 * @link    http://wordpress.stackexchange.com/q/138242/1685
 *
 * @param   string  $sidebar    The database name of the sidebar to add the widget to.
 * @param   string  $name       The database name of the widget.
 * @param   mixed   $args       The widget arguments (optional).
 */
function wpse_138242_pre_set_widget( $sidebar, $name, $args = array() ) {
    if ( ! $sidebars = get_option( 'sidebars_widgets' ) )
        $sidebars = array();

    // Create the sidebar if it doesn't exist.
    if ( ! isset( $sidebars[ $sidebar ] ) )
        $sidebars[ $sidebar ] = array();

    // Check for existing saved widgets.
    if ( $widget_opts = get_option( "widget_$name" ) ) {
        // Get next insert id.
        ksort( $widget_opts );
        end( $widget_opts );
        $insert_id = key( $widget_opts );
    } else {
        // None existing, start fresh.
        $widget_opts = array( '_multiwidget' => 1 );
        $insert_id = 0;
    }

    // Add our settings to the stack.
    $widget_opts[ ++$insert_id ] = $args;
    // Add our widget!
    $sidebars[ $sidebar ][] = "$name-$insert_id";

    update_option( 'sidebars_widgets', $sidebars );
    update_option( "widget_$name", $widget_opts );
}

In your case:

wpse_138242_pre_set_widget( 'footer-left', 'text',
    array(
        'title' => 'Test1',
        'text' => 'Test 1 Test',
        'filter' => false,
    )
);

wpse_138242_pre_set_widget( 'footer-right', 'text',
    array(
        'title' => 'Test2',
        'text' => 'Test 2 Test',
        'filter' => false,
    )
);

Leave a Comment