We’ve created a lot of plugins so far. Some are harmless and others take up space in our WordPress installation. Today, we’ll learn about uninstalling a plugin.
We’ll be working with the same plugin we created in the last tutorial. By creating an option, we’ve also created a column in the database. If a user uninstalls your plugin, then that option will still be stored in that database. Even though the files are gone, your plugin still leaves behind some data. We can and should fix this by creating an uninstall file.
If you view all the installed plugins, you’ll also notice you have an option to delete them. When someone deletes your plugin, WordPress will also run your uninstall file. In an earlier tutorial, I talked about the uninstall file briefly. This file should be included in all your plugins and should be in the root directory of your plugin.
Right now, our uninstall.php file is blank. Let’s add this simple bit of code to our file.
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
if ( get_option( 'jk_op_array' ) != false )
delete_option( 'jk_op_array' );
Uninstalling a Plugin
Before we do anything, we need to check if our plugin is actually being uninstalled. Uninstalling a plugin can not be undone once a user visits the file. If an outsider visits your uninstall file, then they’ll end up deleting all options and settings for your plugin. By checking if the constant WP_UNINSTALL_PLUGIN is defined, we prevent this from happening. If the constant isn’t defined, we then exit out of the script.
When WordPress runs this file, the constant is defined and so the script runs. In our case, we check if the option jk_op_array is an actual option in the options table. If it is, then use the function delete_option() to delete our option. This function takes in 1 argument, the name of our option. Once this script runs, WordPress goes onto uninstalling a plugin. It deletes all files.
There is a difference between deactivating and uninstalling a plugin. If someone uninstalls your plugin, you should assume you should erase as much data left behind from your plugin as possible. Whereas deactivating a plugin, you should only keep things minimal. You can find more information about uninstalling a plugin here.