widgets_init
云策文档标注
概述
widgets_init 是一个 WordPress 动作钩子,在所有默认 WordPress 小工具注册完成后触发。它常用于注册自定义小工具或侧边栏,是主题和插件开发中的关键钩子。
关键要点
- widgets_init 钩子在所有默认 WordPress 小工具注册后触发,通常用于注册自定义小工具或侧边栏。
- 该钩子作为 init 钩子的一部分触发,优先级为 1,意味着它会先于默认优先级的 init 钩子代码执行。
- 在禁用插件注册的小工具时,如果插件使用 widgets_init 钩子,可能需要通过优先级为 0 的 init 动作来移除小工具。
代码示例
function mytheme_widgets_init() {
register_sidebar( array(
'name' => __( 'Single Post Widgets', 'textdomain' ),
'id' => 'mytheme-single-post-widgets',
'description' => __( 'Widgets in this area will be shown under your single posts, before comments.', 'textdomain' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
}
add_action( 'widgets_init', 'mytheme_widgets_init' );注意事项
- widgets_init 钩子与 init 钩子关联,优先级为 1,需注意执行顺序以避免冲突。
- 在移除由插件通过 widgets_init 注册的小工具时,应使用优先级为 0 的 init 动作来确保正确执行。
原文内容
Fires after all default WordPress widgets have been registered.
Source
do_action( 'widgets_init' );
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 3 content
markcallen
You should note that the
widgets_inithook is fired as part of theinithook – with a priority of 1.This means that it will fire before any code you may add to the
inithook with a default priority.add_action( 'init', 'wpdocs_my_init', 0 ); function wpdocs_my_init() { $terms = get_terms( 'ts_product_brand', array( 'hide_empty' => true ) ); if ( ! is_array( $terms ) || count( $terms ) < 2 ) { remove_action( 'widgets_init', 'ts_product_filter_by_brand_load_widget' ); } }Skip to note 4 content
Vail Joy
For example, used with registering sidebars:
function mytheme_widgets_init() { register_sidebar( array( 'name' => __( 'Single Post Widgets', 'textdomain' ), 'id' => 'mytheme-single-post-widgets', 'description' => __( 'Widgets in this area will be shown under your single posts, before comments.', 'textdomain' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); } add_action( 'widgets_init', 'mytheme_widgets_init' );