YogeshChauhan . com

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')) {
    die;
}
 
$option_name = 'wporg_option';
 
delete_option($option_name);
 
// for site options in Multisite
delete_site_option($option_name);
 
// drop a custom database table
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}mytable");


amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What are keys in React?ReactCREATE TABLE Examples in PostgreSQLPostgres3 ways to pass a variable in url() function in SCSS (Sass)SCSSOpen Source Security Tools for Defense SecurityMiscHow to avoid element shift on border change while hovering in CSS?CSSHow to create a Random Hex Color generator using JavaScript?JavaScript