Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 68 ยท Plugins

Activation, Deactivation and Uninstall

Handle the WordPress plugin lifecycle: activation hooks, default options, flushing rewrite rules, uninstall.php cleanup and version-based upgrade routines.

A plugin has a life with distinct moments: it is installed, activated, runs for months, gets updated, is deactivated, and finally deleted. WordPress gives you a hook or a file for most of those moments, and using the right one is the difference between a plugin that behaves politely and one that leaves tables, options and scheduled tasks behind forever. This lesson walks through the lifecycle, shows what to put where, and ends with a runnable lifecycle simulator that handles versions and upgrades.

You should know how a plugin is structured from Your First Plugin and Plugin Structure and Object-Oriented Plugins.

The lifecycle at a glance

stateDiagram-v2
    [*] --> Installed: files copied
    Installed --> Active: activate (activation hook)
    Active --> Inactive: deactivate (deactivation hook)
    Inactive --> Active: activate again
    Active --> Active: update (version check on load)
    Inactive --> [*]: delete (uninstall.php)

Activation and deactivation are reversible; uninstall happens only when an inactive plugin is deleted.

Two things in that picture surprise beginners. First, there is no hook for updates: when a plugin file is replaced by a newer version, nothing fires, so you detect upgrades yourself by comparing a stored version number. Second, uninstall happens only after deactivation, because WordPress deletes inactive plugins.

Activation hooks

register_activation_hook() runs a callback once when an administrator activates the plugin. Call it from the main plugin file, passing __FILE__, so WordPress can match the hook to the right plugin.

PHP
register_activation_hook( __FILE__, 'nwn_activate' );

function nwn_activate() {
	add_option( 'nwn_version', NWN_VERSION );
	add_option( 'nwn_settings', array( 'text' => 'Thanks for reading!' ) );

	nwn_register_event_post_type();
	flush_rewrite_rules();
}

Use activation for one-time setup:

  • Default options. Use add_option(), which does nothing if the option already exists, so reactivating never overwrites a site owner's saved settings. update_option() would.
  • Custom tables. Create or upgrade them here (see $wpdb and Custom Tables).
  • Capability setup and scheduled events.
  • Requirement checks. If the PHP version is too old, deactivate and stop with a clear message rather than crashing later.

An activation callback runs in a special request, not during normal page loads, so do not rely on hooks that fire later (such as init) having run for the callback. If you need a custom post type registered before flushing rewrite rules, call the registration function directly, as the example does.

Activation hooks are not called when a plugin is updated, not on every page load, and not for must-use plugins. On multisite, a network-wide activation runs the hook once for the network, not once per site, so per-site setup needs extra care.

Flushing rewrite rules, but only here

Pretty permalinks for a custom post type or a custom rewrite rule are stored in the database. They are only rebuilt when you call flush_rewrite_rules(), which is an expensive operation. The rule is simple: flush on activation and deactivation only, never on every request. Registering a post type on init makes it exist; flushing once on activation makes its URLs work. Running a flush on every page load slows every request and writes to the database each time. Rewrite rules have their own lesson in Permalinks and Rewrite Rules.

Deactivation hooks

register_deactivation_hook() runs when the plugin is switched off. Deactivation is temporary: the owner may turn the plugin back on tomorrow, so be conservative.

PHP
register_deactivation_hook( __FILE__, 'nwn_deactivate' );

function nwn_deactivate() {
	wp_clear_scheduled_hook( 'nwn_daily_cleanup' );
	flush_rewrite_rules();
}

Typical deactivation work: remove scheduled events (a plugin that is off cannot run them), and flush rewrite rules so URLs of the vanished post type stop resolving. Do not delete user data or options here; that is the job of uninstall. Someone who deactivates to debug a conflict should get the site back exactly as it was.

Uninstall: uninstall.php or a hook

When an administrator deletes a plugin in wp-admin, WordPress offers you two ways to clean up.

1. uninstall.php. A file named exactly that, in the plugin's root folder, runs when the plugin is deleted. It must check that WordPress is calling it:

PHP
<?php
// uninstall.php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

delete_option( 'nwn_version' );
delete_option( 'nwn_settings' );

global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}nwn_log" );

WP_UNINSTALL_PLUGIN is defined only by core's delete flow, so the guard keeps the file from running if someone visits it directly. The plugin's other code is not loaded while uninstall.php runs, so the file must stand alone; it cannot call your classes unless it includes them itself.

2. register_uninstall_hook(). You register a callback from the main file:

PHP
register_uninstall_hook( __FILE__, 'nwn_uninstall' );

WordPress stores the callback in the database, and runs it on deletion after loading the plugin file. The callback should be a function name or a static method, not a closure, because it is stored and cannot be serialized. Use one of the two methods, not both. For most plugins uninstall.php is the simpler, more visible choice.

Deleting user content during uninstall is destructive and cannot be undone. Many plugins delete their own settings and tables but keep content that site owners created, such as posts of a custom post type, unless a setting named something like "Remove all data on uninstall" is switched on.

Version checks and upgrade routines

Because updating fires no hook, store a version number in an option and compare it when the plugin loads. If the stored version is older than the code's version, run the upgrade steps in order, then save the new version.

PHP
add_action( 'plugins_loaded', 'nwn_maybe_upgrade' );

function nwn_maybe_upgrade() {
	$installed = get_option( 'nwn_version', '0' );

	if ( version_compare( $installed, NWN_VERSION, '>=' ) ) {
		return;
	}

	if ( version_compare( $installed, '1.1.0', '<' ) ) {
		// Add the column or option that 1.1.0 introduced.
	}
	if ( version_compare( $installed, '1.2.0', '<' ) ) {
		// Convert the old setting format.
	}

	update_option( 'nwn_version', NWN_VERSION );
}

Each step is guarded by version_compare(), so a site jumping from 1.0.0 to 1.2.0 runs both steps, and a site already on 1.1.0 runs only the second. Make each step safe to run twice, because two requests can arrive at once right after an update. This cheap comparison costs one option read per request, which is almost free because options are usually autoloaded.

The simulator below acts out the whole lifecycle with plain PHP. The "database" is an array of options and the "plugin" is a set of callbacks. It is a stand-in, not WordPress: it shows activation using add_option semantics, the update path with version-guarded migrations, deactivation, and uninstall cleanup.

PHP A plugin lifecycle runner with migrations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice three things in the output. The settings saved at activation survive reactivation, because add_option never overwrites. The upgrade runs both migrations in order exactly once, and a second page load does nothing. And deactivation clears the scheduled event but keeps the options, while uninstall removes the options.

A checklist

Moment Do Do not
Activation Add default options, create tables, check requirements, flush rewrite rules Assume init has run, or overwrite existing settings
Deactivation Clear scheduled events, flush rewrite rules Delete user data
Update Compare stored version, run guarded steps, save the new version Expect a hook to tell you
Uninstall Remove options, tables and transients you created Leave orphaned data, or delete content the user may want

Next you will store structured data of your own in $wpdb and Custom Tables, where activation and uninstall do most of their real work.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use add_option() rather than update_option() for defaults during activation?

    Reactivating a plugin should keep the owner's saved settings. add_option() leaves an existing option untouched.
  2. 2. How does a plugin find out that it was updated to a new version?

    There is no update hook. Plugins store a version in an option and run upgrade steps when the code's version is newer.
  3. 3. When should flush_rewrite_rules() normally be called in a plugin?

    Flushing rebuilds stored rules and is expensive. Do it once when the rules change: on activation and deactivation.
  4. 4. What must uninstall.php check before deleting anything?

    WP_UNINSTALL_PLUGIN is defined only when core runs the file during deletion, which blocks direct access.
  5. 5. What belongs in a deactivation hook?

    Deactivation is reversible, so keep data and clean up only what cannot work while the plugin is off.

Summary

  • register_activation_hook() does one-time setup: default options with add_option(), tables, requirement checks and a rewrite flush.
  • register_deactivation_hook() clears scheduled events and flushes rules; it must not delete user data.
  • Uninstall cleanup lives in uninstall.php (guarded by WP_UNINSTALL_PLUGIN) or register_uninstall_hook().
  • No hook fires on update: store a version and run guarded, repeatable upgrade steps on load.
  • Flush rewrite rules only on activation and deactivation, never per request.
  • The runner above is a stand-in for the lifecycle, not WordPress itself.

Next up: $wpdb and Custom Tables.