3

What I am trying to do is pre-populate the sidebar widget area with some default widgets on theme activation.

if ( ! dynamic_sidebar( 'sidebar' ) ) :

does add the widgets but it doesnot show up in the sidebar of widgets section and

if ( is_active_sidebar( 'sidebar' ) ) {

this function doesnot work if the widgets are not loaded in the sidebar widgetized area.

I know it is possible but I am just out of idea. I googled but didnot find any solutions. Thank you for any help in advance.

4

2 回答 2

8

如果您使用after_switch_theme钩子,但您需要设置小部件的那一刻,您的回答并不清楚。

要激活小部件,我建议将其直接写入数据库,get_option('sidebars_widgets')其中应该提供一个数组,并使用update_option('sidebars_widgets', $new_activated_widgets).

这应该可以帮助您入门。

/**
 * 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);

经过测试,只需将其粘贴到functions.php您的主题中即可。

于 2012-08-01T11:46:43.840 回答
1

如果其他人需要知道如何将多个默认小部件(不同的实例)同时添加到多个侧边栏,以下代码会将小部件添加到页面和管理小部件选项卡下。我意识到这可能对除了我之外的所有人来说都是显而易见的。

所以基于janw和kcssm的努力:

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);

但是,这将删除任何其他设置,因此请小心操作!

于 2014-08-06T13:01:21.917 回答