Defining Default Sidebar Widgets with Theme Functions

Hello guys.

I have a child-theme that will be available for clients in my network. I would like this theme to have a function that specifies which wordpress widgets will be activated for the sidebar automatically when they activate the theme.

The sidebar is registered in the parent theme.

Thank you for your help!

  • Adam Czajczyk

    Hey Carlos,

    I hope you're well today and thanks for your question!

    To activate widgets "by default" upon theme activation you may want to try this code:

    define('WIDGET_INFO', serialize(array(
        'sidebar' => array('id' => 'my-sidebar', 'name' => 'My Sidebar'),
        'widgets' => array(
            'my-subscribe',
            'my-search',
            'my-calendar',
            'my-poll',
            'my-recent-comments',
            'my-more-blogs',
            'my-categories'
        )
    )));
    
    // Everytime you create a new blog, enable all the widgets.
    function add_default_widgets($blog_id)  {
    
        $widget_info = unserialize(WIDGET_INFO);
    
        // We are simply putting the widgets into the table when a blog is created
        foreach($widget_info['widgets'] as $widget_id){
            update_option('widget_' . $widget_id, array());
        }
    
        // Tell what sidebar to have what widgets
        update_option('sidebars_widgets', array($widget_info['sidebar']['id'] => $widget_info['widgets']));
    
        return;
    
    }
    
    // Call the populate_options action on blog creation
    add_action('populate_options', 'add_default_widgets');

    This is Jordan's Boesch plugin to automatically activate custom widgets in Multisite environment but I think that it can be tweaked a bit.

    Place this code in your theme's functions.php file and then:

    1. Replace the sidebar's ID and name with your theme's sidebar:

    'sidebar' => array('id' => 'my-sidebar', 'name' => 'My Sidebar'),

    2. Replace widgets id's with the id's of already existing widget's that you wish to activate:

    'widgets' => array(
            'my-subscribe',
    ...

    Let me know please if it worked for you!

    Cheers,
    Adam

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.