激活和停用钩子提供了在激活或停用插件时执行操作的方法。
- 激活时,插件可以运行例程来添加重写规则、添加自定义数据库表或设置默认选项值。
- 停用后,插件可以运行例程来删除临时数据,例如缓存和临时文件和目录。
警报:停用钩子有时会与卸载钩子混淆。卸载钩子最适合永久删除所有数据,例如删除插件选项和自定义表等。
激活
要设置激活挂钩,请使用 register_activation_hook() 函数:
register_activation_hook(
__FILE__,
'pluginprefix_function_to_run'
);
停用
要设置停用钩子,请使用 register_deactivation_hook()函数:
register_deactivation_hook(
__FILE__,
'pluginprefix_function_to_run'
);
每个函数中的第一个参数是指您的主插件文件,该文件是您在其中放置插件头注释的文件。通常这两个函数将从主插件文件中触发;但是,如果函数放置在任何其他文件中,则必须更新第一个参数以正确指向主插件文件。
示例
激活钩子最常见的用途之一是在插件注册自定义帖子类型时刷新WordPress永久链接。这摆脱了令人讨厌的 404 错误。
让我们看一个如何执行此操作的示例:
/**
* 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' );
如果您不熟悉注册自定义帖子类型,请不要担心,这将在后面介绍。使用此示例只是因为它非常常见。
使用上面的例子,以下是如何逆转此过程并停用插件:
/**
* 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' );
有关激活和停用钩子的更多信息,这里有一些优秀的资源:
- register_activation_hook() 在 WordPress 函数参考中。
- register_deactivation_hook() 在 WordPress 函数参考中。