how to populate widgets on sidebar on theme activation

Deadly 提交于 2019-12-04 16:35:32
janw

It isn't clear from your answer if you use the after_switch_theme hook but that the moment you need to set the widgets.

To activate the widgets I suggest writing it directly into the database with get_option('sidebars_widgets') which should give an array, and save it with update_option('sidebars_widgets', $new_activated_widgets).

This should help you get started.

/**
 * set new widgets on theme activate
 * @param string $old_theme
 * @param WP_Theme $WP_theme
 */
function set_default_theme_widgets ($old_theme, $WP_theme = null) {
    // check if the new theme is your theme
    // figure it out
    var_dump($WP_theme);

    // the name is (probably) the slug/id
    $new_active_widgets = array (
        'sidebar-name' => array (
            'widget-name-1',
            'widget-name-2',
            'widget-name-3',
        ),
        'footer-sidebar' => array(
            'widget-name-1',
            'widget-name-2',
            'widget-name-3',
        )
    );

    // save new widgets to DB
    update_option('sidebars_widgets', $new_active_widgets);
}
add_action('after_switch_theme', 'set_default_theme_widgets', 10, 2);

Tested, just paste it in functions.php of your theme.

If anyone else needed to know how to add multiple default widgets (different instances) to multiple sidebars at the same time, the following code will add the widgets both to the page and under the admin widget tab. I realize that this may have been obvious to everyone but me.

So based on janw and kcssm's hard work:

function add_theme_widgets($old_theme, $WP_theme = null) {

    $activate = array(
        'right-sidebar' => array(
            'recent-posts-1', 
            'categories-1', 
            'archives-1'
        ), 
        'footer-sidebar' => array(
            'recent-posts-2', 
            'categories-2', 
            'archives-2'
        )
    );

    /* the default titles will appear */
    update_option('widget_recent-posts', array(
        1 => array('title' => ''), 
        2 => array('title' => '')));

    update_option('widget_categories', array(
        1 => array('title' => ''), 
        2 => array('title' => '')));

    update_option('widget_archives', array(
        1 => array('title' => ''), 
        2 => array('title' => '')));

    update_option('sidebars_widgets',  $activate);
}

add_action('after_switch_theme', 'add_theme_widgets', 10, 2);

This will however delete any other settings, so tread carefully!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!