如何在主题激活时填充侧边栏上的小部件 [英] how to populate widgets on sidebar on theme activation
问题描述
我想要做的是在主题激活时使用一些默认小部件预先填充侧边栏小部件区域.
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.
推荐答案
如果你使用 after_switch_theme
钩子,但那一刻你需要设置小部件.
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.
要激活小部件,我建议使用 get_option('sidebars_widgets')
将其直接写入数据库,这应该提供一个数组,并使用 update_option('sidebars_widgets', $new_activated_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);
已测试,只需将其粘贴到您主题的 functions.php
中即可.
Tested, just paste it in functions.php
of your theme.
这篇关于如何在主题激活时填充侧边栏上的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!