Yogesh Chauhan's Blog

How to clean up after a plugin uninstall in WordPress?

in WordPress on June 7, 2021

When the user uninstalls your plugin, you have a clean up job to do. Basically when a user clicks on delete plugin after deactivation it, your plugin should be removed WITH a bit clean up.

You usually would want to remove the plugin specific settings, options or some database entries.

Deactivation hook and uninstall hooks perform different tasks.

The deactivation hook flushes caches/temp files and permalinks while uninstall hook removes options from {$wpdb->prefix}_options and tables from wpdb

Methods to setup the uninstall hook

You can use either of these 2 methods to setup the uninstall hook.

Use register_uninstall_hook() like this:

register_uninstall_hook(__FILE__, 'function');

Creating a uninstall.php file

You create the uninstall.php file in the root folder of your plugin.

The uninstall.php file is run automatically when the plugin is deleted.

To protect against direct access, a good practice is to check for the constant WP_UNINSTALL_PLUGIN in the uninstall.php file before adding other code.

Example from WordPress

This code in uninstall.php file will delete option entries and will drop a database table.

// if uninstall.php is not called by WordPress, die
if (!defined('WP_UNINSTALL_PLUGIN')) {
$option_name = 'wporg_option';
// for site options in Multisite
// drop a custom database table
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}mytable");

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Data Flows in ReactReactMoving folders in WordPress using codeWordPressRendering Elements in ReactReactAttributes and Properties in JavaScript and HTMLHTMLVariables scope and shadowing in SCSS (Sass)SCSSHow to change HTML content on click using JavaScript?JavaScript