is_active_sidebar()
云策文档标注
概述
is_active_sidebar() 函数用于检查指定侧边栏是否包含小工具,返回布尔值。它基于 wp_get_sidebars_widgets() 获取小工具列表,并通过过滤器 is_active_sidebar 允许自定义判断逻辑。
关键要点
- 参数 $index 为字符串或整数,表示侧边栏的名称、ID 或编号,函数会将其转换为标准格式(如整数转为 "sidebar-$index",字符串通过 sanitize_title() 处理)。
- 返回值为布尔值:如果侧边栏包含小工具则返回 true,否则返回 false。
- 函数内部使用 apply_filters('is_active_sidebar', $is_active_sidebar, $index) 钩子,允许开发者过滤判断结果。
- 注意:通过名称搜索侧边栏时,需确保 register_sidebar 调用时明确声明了 ID,且 ID 与 sanitize_title($sidebar_name) 完全匹配,否则可能无法正确识别。
代码示例
// 示例:根据侧边栏是否活动显示不同输出
if ( is_active_sidebar( 'sidebar-1' ) ) {
// 侧边栏包含小工具时的代码
} else {
// 侧边栏为空时的代码
}
原文内容
Determines whether a sidebar contains widgets.
Description
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
$indexstring|intrequired-
Sidebar name, id or number to check.
Source
function is_active_sidebar( $index ) {
$index = ( is_int( $index ) ) ? "sidebar-$index" : sanitize_title( $index );
$sidebars_widgets = wp_get_sidebars_widgets();
$is_active_sidebar = ! empty( $sidebars_widgets[ $index ] );
/**
* Filters whether a dynamic sidebar is considered "active".
*
* @since 3.9.0
*
* @param bool $is_active_sidebar Whether or not the sidebar should be considered "active".
* In other words, whether the sidebar contains any widgets.
* @param int|string $index Index, name, or ID of the dynamic sidebar.
*/
return apply_filters( 'is_active_sidebar', $is_active_sidebar, $index );
}
Hooks
- apply_filters( ‘is_active_sidebar’, bool $is_active_sidebar, int|string $index )
-
Filters whether a dynamic sidebar is considered “active”.
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 4 content
Codex
Example
Display different output depending on whether the sidebar is active or not.
<ul id="sidebar"> </ul>Skip to note 5 content
drdogbot7
In the description: “in use” means that the sidebar contains widgets.
Any sidebar that contains widgets will return TRUE, whereas any sidebar that does not contain any widgets will return FALSE.
Skip to note 6 content
Isaac Lubow
Note that you cannot search by sidebar name if the ID was not specifically declared when register_sidebar was called, and even then only when the ID is exactly the value of
sanitize_title($sidebar_name).The simple method used by the code (see above) is the reason for this:
$index = ( is_int($index) ) ? "sidebar-$index" : sanitize_title($index);