is_active_widget()
概述
is_active_widget() 函数用于判断指定的小部件是否在前端显示。它通过检查小部件的回调函数或基础ID,返回小部件活跃的侧边栏ID,若无活跃实例则返回false。
关键要点
- 函数接受参数 $callback、$widget_id、$id_base 和 $skip_inactive,用于指定小部件和检查范围。
- 返回值为字符串(侧边栏ID)或 false(小部件未激活)。
- 函数需在 widgets 初始化后运行,例如在 'init' action 之后。
- 对于单个小部件,$widget_id 和 $id_base 通常相同。
代码示例
if ( is_active_widget( false, false, 'recent-posts', true ) ) {
wp_enqueue_script( 'jquery' );
}注意事项
注意 $widget_id 和 $id_base 在单小部件中的一致性,并确保函数在适当时机调用以避免错误。
Determines whether a given widget is displayed on the front end.
Description
Either $callback or $id_base can be used.
$id_base is the first argument when extending WP_Widget class.
Without the optional $widget_id parameter, returns the ID of the first sidebar in which the first instance of the widget with the given callback or $id_base is found.
With the $widget_id parameter, returns the ID of the sidebar where the widget with that callback/$id_base AND that ID is found.
NOTE: $widget_id and $id_base are the same for single widgets. To be effective this function has to run after widgets have initialized, at action ‘init’ or later.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
$callbackcallable|falseoptional-
Widget callback to check.
Default:
false $widget_idstring|falseoptional-
Widget ID. Optional, but needed for checking.
Default:
false $id_basestring|falseoptional-
The base ID of a widget created by extending WP_Widget.
Default:
false $skip_inactivebooloptional-
Whether to check in
'wp_inactive_widgets'.
Default:
true
Source
function is_active_widget( $callback = false, $widget_id = false, $id_base = false, $skip_inactive = true ) {
global $wp_registered_widgets;
$sidebars_widgets = wp_get_sidebars_widgets();
if ( is_array( $sidebars_widgets ) ) {
foreach ( $sidebars_widgets as $sidebar => $widgets ) {
if ( $skip_inactive && ( 'wp_inactive_widgets' === $sidebar || str_starts_with( $sidebar, 'orphaned_widgets' ) ) ) {
continue;
}
if ( is_array( $widgets ) ) {
foreach ( $widgets as $widget ) {
if ( ( $callback && isset( $wp_registered_widgets[ $widget ]['callback'] ) && $wp_registered_widgets[ $widget ]['callback'] === $callback ) || ( $id_base && _get_widget_id_base( $widget ) === $id_base ) ) {
if ( ! $widget_id || $widget_id === $wp_registered_widgets[ $widget ]['id'] ) {
return $sidebar;
}
}
}
}
}
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 2 content
Codex
Only load a script when the widget is active
id_base, true ) ) { wp_enqueue_script( 'jquery' ); } ?>