wp_assign_widget_to_sidebar()
云策文档标注
概述
wp_assign_widget_to_sidebar() 函数用于将指定的小部件分配到给定的侧边栏,通过更新侧边栏小部件列表实现。它首先从现有侧边栏中移除小部件,然后将其添加到目标侧边栏。
关键要点
- 函数接受两个必需参数:$widget_id(小部件ID)和$sidebar_id(侧边栏ID)。
- 如果$sidebar_id为空,小部件不会被添加到任何侧边栏,仅从原侧边栏移除。
- 函数内部使用wp_get_sidebars_widgets()获取当前侧边栏小部件配置,并调用wp_set_sidebars_widgets()更新配置。
- 该函数在WordPress 5.8.0版本中引入,主要用于REST API控制器处理小部件的创建、更新和删除操作。
代码示例
function wp_assign_widget_to_sidebar( $widget_id, $sidebar_id ) {
$sidebars = wp_get_sidebars_widgets();
foreach ( $sidebars as $maybe_sidebar_id => $widgets ) {
foreach ( $widgets as $i => $maybe_widget_id ) {
if ( $widget_id === $maybe_widget_id && $sidebar_id !== $maybe_sidebar_id ) {
unset( $sidebars[ $maybe_sidebar_id ][ $i ] );
// We could technically break 2 here, but continue looping in case the ID is duplicated.
continue 2;
}
}
}
if ( $sidebar_id ) {
$sidebars[ $sidebar_id ][] = $widget_id;
}
wp_set_sidebars_widgets( $sidebars );
}注意事项
函数在循环中处理小部件ID重复的情况,即使找到匹配项也会继续遍历以确保所有实例被移除。相关函数包括wp_get_sidebars_widgets()和wp_set_sidebars_widgets(),用于获取和设置侧边栏小部件配置。
原文内容
Assigns a widget to the given sidebar.
Parameters
$widget_idstringrequired-
The widget ID to assign.
$sidebar_idstringrequired-
The sidebar ID to assign to. If empty, the widget won’t be added to any sidebar.
Source
function wp_assign_widget_to_sidebar( $widget_id, $sidebar_id ) {
$sidebars = wp_get_sidebars_widgets();
foreach ( $sidebars as $maybe_sidebar_id => $widgets ) {
foreach ( $widgets as $i => $maybe_widget_id ) {
if ( $widget_id === $maybe_widget_id && $sidebar_id !== $maybe_sidebar_id ) {
unset( $sidebars[ $maybe_sidebar_id ][ $i ] );
// We could technically break 2 here, but continue looping in case the ID is duplicated.
continue 2;
}
}
}
if ( $sidebar_id ) {
$sidebars[ $sidebar_id ][] = $widget_id;
}
wp_set_sidebars_widgets( $sidebars );
}
Changelog
| Version | Description |
|---|---|
| 5.8.0 | Introduced. |