Plugin Development

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.

if( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) 
// Uninstall code goes here


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().


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

        foreach($blogs as $blog) 
} else {
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days