卸载方法

从站点卸载插件时,可能需要对其进行一些清理。

如果用户禁用了插件,然后单击WordPress管理中的删除链接,则认为该插件已卸载。

卸载插件时,您需要清除插件的所有插件选项或设置,以及其他数据库实体(如表)。

经验不足的开发人员有时会犯这样的错误:使用禁用钩子。

下表说明了禁用和卸载之间的差异。

场景 禁用钩子 卸载钩子
刷新 Cache/Temp Yes No
刷新 Permalinks Yes No
从 {$wpdb->prefix}_options 删除选项 No Yes
wpdb 删除表 No Yes

 

方法1:register_uninstall_hook

要设置卸载钩子,请使用register_uninstall_hook()函数:

register_uninstall_hook(__FILE__, 'pluginprefix_function_to_run');

 

方法2:uninstall.php

要使用这种方法,您需要在插件的根文件夹中创建一个uninstall.php文件。当用户删除插件时,这个神奇的文件会自动运行。

例如:/plugin-name/uninstall.php

Alert:
在做任何事情之前,始终检查uninstall.php中的常数WP_UNINSTALL_PLUGIN。这可以防止直接访问。

常量将在uninstall.php调用期间由WordPress定义。

register_uninstall_hook()执行卸载时,常量则定义。

以下是删除选项项并删除数据库表的示例:

// 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");

Note:在多站点中,通过所有博客循环删除选项可能会占用大量资源。