There are 3 main events in the lifecycle of a plugin that you can hook into:
- Activation
- Deactivation
- Uninstall
Activation happens when the user clicks “Activate” after installing your plugin. You can hook a callback function to this event using the register_activation_hook() function. Some of the most common tasks to do here are:
- Adding options (if you need to control autoload or are not using the Settings API).
- Creating database tables (if you’re using custom tables).
- Flushing rewrite rules (if you’re registering custom post types or anything like that).
- Registering custom cron jobs.
- Redirecting to the welcome/tutorial page.
Deactivation happens when the user clicks “Deactivate”. You can hook a callback function to this event using the register_deactivation_hook() function. It’s important to note that no data should be deleted on the deactivation hook. The user is temporarily turning the plugin off and expects all of their settings to still be there when they turn it back on. Some things to do here are:
- Flushing rewrite rules (similarly as during activation, flush if your plugin changes them).
- Removing custom cron jobs.
- Flushing cache/temp.
Uninstall happens when the user clicks “Delete” after they deactivate the plugin. In contrast to deactivation, this event is supposed to be destructive. The user is getting rid of your plugin. You should delete all data your plugin has added, either in the database or in the filesystem. A good plugin leaves no trace of ever being installed.
There are 2 ways of running the uninstall code: you can either register a callback with register_uninstall_hook() or you can create an uninstall.php file in your plugin’s root directory. The latter is a recommended best practice, as it is loaded in a sandboxed environment and keeps the destructive logic separated from your main plugin files.
Instead of checking for ABSPATH, you should check for WP_UNINSTALL_PLUGIN. Let’s add the uninstall.php to our plugin to delete the reading time text option.
<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'pgn_reading_time_text' );