跳转到主要内容

激活/停用挂钩

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

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

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

激活

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

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