
Using Uninstall Hook to Delete Plugin
- March 25, 2016
- Leave a comment
When you install a plugin, you may create different database entries or define rewrite rules. On deleting a plugin, it may require a cleanup as you do upon plugin activation. The items that should be clear out can be rewrite rules added by the plugin, options/settings specific to the plugin, or other database values. It is not encouraged to write a code on deactivation hook as user may want to reactivate the plugin with older data.
Instead of writing a code in deactivation hook, uninstall.php file containing the hook should be used. This hook checks the WP_UNINSTALL_PLUGIN constant before proceeding the plugin deletion.
The WP_UNINSTALL_PLUGIN constant is defined by WordPress only if an uninstall.php file is present in the plugin folder. It cannot be accessed directly except at the time of plugin being deleted.
Here is an example of uninstall.php file that performs different operations on executing plugin delete request:
1 2 3 4 5 6 7 8 9 10 |
If ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit(); } $myoption_name = 'my_plugin_option_name'; // Delete option from wp_options delete_option( $myoption_name ); // Drop table from database global $wpdb; $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytablename" ); |
<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'ip2location_widget_type' );
delete_option( 'ip2location_widget_language' );
delete_option( 'ip2location_widget_debug_log_enabled' );
wp_cache_flush();