Uninstall Hook For WordPress Plugin

When a user deletes your WordPress plugin it might be necessary that you do some processing for cleaning up the WordPress site. This is because a WordPress plugin can be used to create new data such as post types, options meta, post meta, custom tables etc. On the deleting event you may need to perform tasks such as removing this custom data the plugin has created. There are a couple of ways you can do this, you can either use the register_uninstall_hook or have a uninstall.php file in the root of your plugin folder. When the user decides they want to uninstall the plugin WordPress will then run the code in this hook or in the uninstall.php file.

Creating The Uninstall.php File

Start the file by checking that the WP_UNINSTALL_PLUGIN constant is defined, this will make sure that no one can view the file directly and execute the uninstall script for the plugin. On the uninstall action of the plugin WordPress will define WP_UNINSTALL_PLUGIN just before loading the file. Then you can run the remove option functions that you need to clean up the database of the options installed by the plugin.


<?php
 
if( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) 
	exit();
	
// Uninstall code goes here

delete_option('option_name');
delete_option('option_name_2');

WordPress Multisites

Using one WordPress install you can have multiple sites enabled, a plugin could be used to install settings to all these sites, which means when you have an uninstall.php file you will need to remember to switch to all the different sites and remove the data on each site. To switch between the different blogs on your multisite you will use the function switch_to_blog().


switch_to_blog($blog_id);

When you have switched this blog you can use the same delete_option('option') function to delete the settings on each blog.


if (is_multisite()) 
{
    global $wpdb;
    $blogs = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs}", ARRAY_A);

    if(!empty($blogs))
    {
        foreach($blogs as $blog) 
        {
	    switch_to_blog($blog['blog_id']);
            delete_option('option_name');
        }
    }
} else {
    delete_option('option_name');
}

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring