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

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

停用钩子有时会被与卸载钩子混淆。卸载钩子最适合永久删除所有数据,例如删除插件选项和自定义表等。

激活

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

有关激活和停用钩子的更多信息,以下是一些优秀的资源: