1. 主页
  2. 文档
  3. 插件及插件制作
  4. 插件基础
  5. 激活、停用挂钩

激活、停用挂钩

激活和停用挂钩提供了在激活或停用插件时执行操作的方法。

  • 激活,插件可以运行一个程序来添加重写规则,添加自定义数据库表,或设定的默认选项值。
  • 失活,插件可以运行一个程序来删除临时数据,如缓存和临时文件和目录。

停用钩子有时会与卸载钩子混淆。卸载钩子最适合永久删除所有数据,例如删除插件选项和自定义表等。在此处了解有关卸载钩子的更多信息。

激活

要设置激活挂钩,请使用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' );

有关激活和停用挂钩的更多信息,以下是一些出色的资源:

  • WordPress函数参考中的register_activation_hook()。
  • WordPress函数参考中的register_deactivation_hook()。
这篇文章对您有用吗?

我们要如何帮助您?