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.
To use this method you need to create anuninstall.phpfile 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 constantWP_UNINSTALL_PLUGINinuninstall.phpbefore doing anything. This protects against direct access.
The constant will be defined by WordPress during theuninstall.phpinvocation.
Here is an example deleting option entries and dropping a database table:
// if uninstall.php is not called by WordPress, dieif ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {die;}$option_name = 'wporg_option';delete_option( $option_name );// for site options in Multisitedelete_site_option( $option_name );// drop a custom database tableglobal $wpdb;$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
In Multisite, looping through all blogs to delete options can be very resource intensive.