RevealTheme logo
Back to Blog

WordPress Plugin Activation Hooks: What They Do

WordPress Plugin Activation Hooks: What They Do
The RevealTheme Team

By

··3 min read

WordPress plugins can run code at three key lifecycle moments: activation, deactivation, and uninstallation. Each has a specific hook; each has specific use cases; each has specific failure modes when misused.

Understanding the lifecycle helps debug plugin issues and write better custom plugins. The patterns are well-defined.

The activation hook

register_activation_hook() registers a function to run when a plugin is activated. Common uses: create database tables, set default options, schedule cron events.

register_activation_hook(__FILE__, 'my_plugin_activate');
function my_plugin_activate() {
    // One-time setup
}

The hook fires once per activation. Code here runs even if the plugin was previously installed and deactivated.

The deactivation hook

register_deactivation_hook() registers a function for deactivation. Common uses: unschedule cron events, clean up temporary data.

The deactivation should be reversible. The user might reactivate; deactivation shouldn't destroy data that activation would need.

The uninstall hook

register_uninstall_hook() or an uninstall.php file runs when the plugin is deleted. Common uses: remove database tables, delete options, clean up all plugin data.

The uninstall should remove everything the plugin added. Sites accumulate cruft from plugins that don't clean up properly.

The common mistakes

Putting heavy work in activation. The activation hook runs in the request that activated the plugin; long-running tasks block the response.

Forgetting to handle reactivation. The activation may run multiple times across the plugin's life; the code should handle being run again.

Not cleaning up on uninstall. The plugin leaves database rows, options, tables behind after deletion.

The diagnostic value

Plugin issues sometimes trace to activation problems. Failed activations may leave partial state. Reactivation may fix or worsen.

For debugging plugin behavior, the lifecycle hooks are worth checking. The plugin's code can be inspected to see what it does at each stage.

The honest framing

For plugin users, lifecycle hook understanding is rarely needed. The plugin's vendor handles them.

For plugin developers, the hooks are fundamental. Getting them wrong produces plugins that don't install cleanly or don't clean up after themselves.