如何在主题激活的侧栏上填充小部件

kcs*_*ssm 3 wordpress sidebar widget

我想要做的是在主题激活时使用一些默认小部件预填充侧边栏小部件区域.

if ( ! dynamic_sidebar( 'sidebar' ) ) :
Run Code Online (Sandbox Code Playgroud)

添加小部件,但它不会显示在小部件的侧边栏和

if ( is_active_sidebar( 'sidebar' ) ) {
Run Code Online (Sandbox Code Playgroud)

如果窗口小部件未在侧边栏窗口小部件区域中加载,则此功能不起作用.

我知道这是可能的,但我只是出于想法.我用谷歌搜索,但没有找到任何解决方案.感谢您提前提供的任何帮助.

jan*_*anw 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);
Run Code Online (Sandbox Code Playgroud)

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