激活和停用钩子允许插件在激活或停用时执行特定操作,如设置默认值或清理临时数据。这些钩子通过 register_activation_hook() 和 register_deactivation_hook() 函数实现,常用于处理自定义文章类型和重写规则。
// 激活钩子示例:注册自定义文章类型并刷新重写规则
function pluginprefix_activate() {
pluginprefix_setup_post_type();
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
// 停用钩子示例:注销自定义文章类型并刷新重写规则
function pluginprefix_deactivate() {
unregister_post_type( 'book' );
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );Activation and deactivation hooks provide ways to perform actions when plugins are activated or deactivated.
To set up an activation hook, use the register_activation_hook() function:
register_activation_hook(
__FILE__,
'pluginprefix_function_to_run'
);
To set up a deactivation hook, use the register_deactivation_hook() function:
register_deactivation_hook(
__FILE__,
'pluginprefix_function_to_run'
);
The first parameter in each of these functions refers to your main plugin file, which is the file in which you have placed the plugin header comment. Usually these two functions will be triggered from within the main plugin file; however, if the functions are placed in any other file, you must update the first parameter to correctly point to the main plugin file.
One of the most common uses for an activation hook is to refresh WordPress permalinks when a plugin registers a custom post type. This gets rid of the nasty 404 errors.
Let’s look at an example of how to do this:
/**
* Register the "book" custom post type
*/
function pluginprefix_setup_post_type() {
register_post_type( 'book', ['public' => true ] );
}
add_action( 'init', 'pluginprefix_setup_post_type' );
/**
* Activate the plugin.
*/
function pluginprefix_activate() {
// Trigger our function that registers the custom post type plugin.
pluginprefix_setup_post_type();
// Clear the permalinks after the post type has been registered.
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
If you are unfamiliar with registering custom post types, don’t worry – this will be covered later. This example is used simply because it’s very common.
Using the example from above, the following is how to reverse this process and deactivate a plugin:
/**
* Deactivation hook.
*/
function pluginprefix_deactivate() {
// Unregister the post type, so the rules are no longer in memory.
unregister_post_type( 'book' );
// Clear the permalinks to remove our post type's rules from the database.
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );
For further information regarding activation and deactivation hooks, here are some excellent resources: