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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Introduction to components and templates Part 4: Pipes and DirectivesAngularHow to create a sidebar using pure CSS?CSSReverse a String in JavaScriptJavaScriptHow To Create a Fullscreen Background Video using CSS and JavaScript?CSSCREATE DATABASE in PostgreSQLPostgresHow to define variables in SCSS (Sass)?SCSS