插件开发文档

💡 云策文档标注

概述

本文档介绍了 WordPress 插件卸载时的清理方法,包括使用 register_uninstall_hook() 函数和创建 uninstall.php 文件,并强调了卸载与停用的区别。

关键要点

  • 插件卸载发生在用户停用后点击删除链接时,需清理插件选项、设置或数据库表等。
  • 避免错误使用停用钩子进行卸载清理,停用和卸载在缓存刷新、选项删除等方面有不同行为。
  • 提供两种卸载方法:register_uninstall_hook() 函数和 uninstall.php 文件,后者需检查 WP_UNINSTALL_PLUGIN 常量以防止直接访问。
  • 在卸载过程中,可使用 delete_option()、delete_site_option() 和 $wpdb->query() 等函数删除选项和数据库表。
  • 多站点环境中,循环删除所有博客的选项可能资源密集,需谨慎处理。

代码示例

// 使用 register_uninstall_hook() 函数
register_uninstall_hook(
    __FILE__,
    'pluginprefix_function_to_run'
);

// uninstall.php 文件示例
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    die;
}

$option_name = 'wporg_option';
delete_option( $option_name );
delete_site_option( $option_name );

global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );

注意事项

  • 卸载钩子与停用钩子功能不同,应根据场景正确选择。
  • 在 uninstall.php 中必须检查 WP_UNINSTALL_PLUGIN 常量,以确保安全执行。
  • 多站点环境下卸载操作可能影响性能,需优化资源使用。

📄 原文内容

Your plugin may need to do some clean-up when it is uninstalled from a site.

A plugin is considered uninstalled if a user has deactivated the plugin, and then clicks the delete link within the WordPress Admin.

When your plugin is uninstalled, you’ll want to clear out any plugin options and/or settings specific to the plugin, and/or other database entities such as tables.

Less experienced developers sometimes make the mistake of using the deactivation hook for this purpose.

This table illustrates the differences between deactivation and uninstall.

Scenario Deactivation Hook Uninstall Hook
Flush Cache/Temp Yes No
Flush Permalinks Yes No
Remove Options from {$wpdb->prefix}_options No Yes
Remove Tables from wpdb No Yes

Method 1: register_uninstall_hook

To set up an uninstall hook, use the register_uninstall_hook() function:

register_uninstall_hook(
	__FILE__,
	'pluginprefix_function_to_run'
);

Method 2: uninstall.php

To use this method you need to create an uninstall.php file inside the root folder of your plugin. This magic file is run automatically when the users deletes the plugin.

For example: /plugin-name/uninstall.php

Always check for the constant WP_UNINSTALL_PLUGIN in uninstall.php before doing anything. This protects against direct access.

The constant will be defined by WordPress during the uninstall.php invocation.

The constant is NOT defined when uninstall is performed by register_uninstall_hook() .

Here is an example deleting option entries and dropping a database table:

// if uninstall.php is not called by WordPress, die
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    die;
}

$option_name = 'wporg_option';

delete_option( $option_name );

// for site options in Multisite
delete_site_option( $option_name );

// drop a custom database table
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
In Multisite, looping through all blogs to delete options can be very resource intensive.