init
云策文档标注
概述
init 钩子在 WordPress 加载完成后、发送任何头部信息前触发,此时大部分 WordPress 核心已加载且用户已认证。它常用于处理 $_GET 或 $_POST 数据、加载插件文本域等初始化操作。
关键要点
- init 钩子在 WordPress 加载完成但未发送头部时触发,用户已认证,适合执行早期初始化任务。
- 与 admin_init 钩子不同,init 作用于整个 WordPress 初始化,而 admin_init 仅针对后台屏幕或脚本。
- 使用 init 钩子可以拦截 $_GET 或 $_POST 触发器,例如处理表单提交数据。
- load_plugin_textdomain 调用应在 init 钩子中进行,以确保用户能正确挂钩。
- 如果需要在 WordPress 完全加载后执行操作,应使用 wp_loaded 钩子。
- 为避免 init 钩子被多次触发导致代码重复执行,可以使用 did_action('init') 进行检查。
代码示例
add_action( 'init', 'process_post' );
function process_post() {
if( isset( $_POST['unique_hidden_field'] ) ) {
// process $_POST data here
}
}注意事项
- init 钩子适用于处理 $_GET 或 $_POST 数据,但需注意安全性和数据验证。
- 确保 load_plugin_textdomain 在 init 钩子中调用,以支持国际化。
- 使用 did_action('init') 可以检查 init 钩子是否已触发多次,避免重复执行代码。
原文内容
Fires after WordPress has finished loading but before any headers are sent.
Description
Most of WP is loaded at this stage, and the user is authenticated. WP continues to load on the ‘init’ hook that follows (e.g. widgets), and many plugins instantiate themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.).
If you wish to plug an action once WP is loaded, use the ‘wp_loaded’ hook below.
Source
do_action( 'init' );
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Rnaby
This hook works almost like the
admin_inithook. The difference is theadmin_initfires on the initialization of admin screen or scripts and thisinithook fires on the initialization time of the whole WordPress script. Like-/** * Fire on the initialization of WordPress. */ function the_dramatist_fire_on_wp_initialization() { // Do stuff. Say we will echo "Fired on the WordPress initialization". echo 'Fired on the WordPress initialization'; } add_action( 'init', 'the_dramatist_fire_on_wp_initialization' );Now the above code will echo “Fired on the WordPress initialization” on initialization of WordPress.
/* avoid running code twice */ if ( did_action( 'init' ) > 1 ) return false;