WP: Delete Plugin Data On Uninstall

In the previous post, I created a plugin which stores some data in the database. Now I will add some code to it which will help to delete this data when the plugin is deleted or uninstalled via the plugins page.

When a plugin is deleted, the uninstall hook is called. I’m going to register the uninstall hook and ask it to call a function which removes our plugin data for us. Here’s the code for it:

register_uninstall_hook( __FILE__, 'my_fn_uninstall' );
function my_fn_uninstall() {
    delete_option( 'g_first_option' );
    delete_option( 'g_second_option' );
}

I’ve added this to the noice-plugin.php file I created in the previous post. If I try to delete the plugin now, it will display this message to me:

Once I hit OK, it will delete g_first_option and g_second_option from the wp_options table in the database.