Plugin activation, deactivation and uninstall hooks
A plugin has a life cycle: it is activated, runs while active, is deactivated and finally deleted. WordPress has a hook for each of these moments, and each one has its own job. Activation sets things up, deactivation removes temporary side effects but keeps the data, and uninstall removes everything the plugin created. Mixing them up leaves either missing tables or data that stays in the database forever.
Problem: A plugin needs a database table and default options when it is activated, must stop its cron event when it is deactivated, and should leave nothing behind when it is deleted.
Solution: Create tables and options in register_activation_hook(), unschedule events and flush rewrite rules in register_deactivation_hook(), and delete data in an uninstall.php file in the plugin folder.
Activation
<?php
/**
* Plugin Name: HA Logger
*/
register_activation_hook( __FILE__, 'ha_logger_activate' );
function ha_logger_activate() {
global $wpdb;
$table = $wpdb->prefix . 'ha_logs';
$charset = $wpdb->get_charset_collate();
// dbDelta needs exactly "CREATE TABLE name (", one field per line and two spaces after PRIMARY KEY
$sql = "CREATE TABLE $table (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
event_type varchar(100) NOT NULL,
message text NOT NULL,
created_at datetime NOT NULL,
PRIMARY KEY (id),
KEY event_type (event_type)
) $charset;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
add_option( 'ha_logger_settings', array( 'level' => 'error' ) ); // does nothing if the option exists
update_option( 'ha_logger_db_version', '1.0' );
if ( ! wp_next_scheduled( 'ha_logger_cleanup' ) ) {
wp_schedule_event( time(), 'daily', 'ha_logger_cleanup' );
}
}
dbDelta() creates the table or updates it to the new definition, so the same function can run again for an upgrade. Do not write CREATE TABLE IF NOT EXISTS: dbDelta then reads “IF” as the table name.
The activation hook runs only when the plugin is activated in the admin (or with wp plugin activate). It does not run after an update, so compare the stored ha_logger_db_version on plugins_loaded and call the setup again when it is older than the current version.
Deactivation
<?php
register_deactivation_hook( __FILE__, 'ha_logger_deactivate' );
function ha_logger_deactivate() {
wp_clear_scheduled_hook( 'ha_logger_cleanup' ); // remove all scheduled runs
flush_rewrite_rules(); // if the plugin added rewrite rules
}
Do not delete settings or tables here. Deactivation is often temporary: while looking for a plugin conflict, for example, and users expect their settings back when they activate the plugin again. Why rewrite rules are flushed in these hooks is explained in rewrite rules and flushing.
Uninstall
When the plugin is deleted in the admin, WordPress runs uninstall.php from its folder, if it exists, without loading the plugin itself:
<?php
// uninstall.php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit; // not called by WordPress
}
global $wpdb;
delete_option( 'ha_logger_settings' );
delete_option( 'ha_logger_db_version' );
delete_metadata( 'post', 0, '_ha_logger_data', '', true ); // this meta key of all posts
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}ha_logs" );
The alternative, register_uninstall_hook(), needs a function or a static method (no closures) and is stored in the database on activation. The file is simpler and is what most plugins use.
NOTE: All three hooks must be registered in the main plugin file with __FILE__ of that file: WordPress identifies the plugin by its main file. In Multisite, network activation runs the activation hook only once, for the main site; a plugin with per-site tables must create them for the other sites itself, for example when a site is first used.