wp_get_sidebar()
云策文档标注
概述
wp_get_sidebar() 函数用于根据给定的 ID 检索已注册的侧边栏。它返回侧边栏的数组信息,若未注册则返回 null。
关键要点
- 参数 $id 为字符串类型,必需,表示侧边栏的 ID。
- 返回值类型为数组或 null,返回找到的侧边栏数组,若未注册则返回 null。
- 函数内部遍历全局变量 $wp_registered_sidebars 来匹配 ID。
- 特殊处理 ID 为 'wp_inactive_widgets' 的情况,返回一个预定义的数组。
- 该函数在 WordPress 5.9.0 版本中引入。
代码示例
function wp_get_sidebar( $id ) {
global $wp_registered_sidebars;
foreach ( (array) $wp_registered_sidebars as $sidebar ) {
if ( $sidebar['id'] === $id ) {
return $sidebar;
}
}
if ( 'wp_inactive_widgets' === $id ) {
return array(
'id' => 'wp_inactive_widgets',
'name' => __( 'Inactive widgets' ),
);
}
return null;
}注意事项
- 函数依赖于全局变量 $wp_registered_sidebars,确保侧边栏已正确注册。
- 对于 'wp_inactive_widgets' ID,函数返回一个硬编码数组,无需注册即可使用。
- 相关函数包括 __() 用于翻译,以及 REST API 控制器中的权限检查函数。
原文内容
Retrieves the registered sidebar with the given ID.
Parameters
$idstringrequired-
The sidebar ID.
Source
function wp_get_sidebar( $id ) {
global $wp_registered_sidebars;
foreach ( (array) $wp_registered_sidebars as $sidebar ) {
if ( $sidebar['id'] === $id ) {
return $sidebar;
}
}
if ( 'wp_inactive_widgets' === $id ) {
return array(
'id' => 'wp_inactive_widgets',
'name' => __( 'Inactive widgets' ),
);
}
return null;
}
Changelog
| Version | Description |
|---|---|
| 5.9.0 | Introduced. |