What are activation and deactivation hooks?
They are just hooks that helps perform different actions when WordPress plugins are activated or deactivated by the user.
There are few things to check or perform when a user activates a plugin. Those are routine tasks such as adding rewrite rules into .htaccess (or just in PHP file), add or update some data into a database, set some default option values for the user etc.
Same way we update or remove data and perform some other tasks when removing a plugin. The removable data include any temporary data saved by the plugin such as cache files, temp files or even directories.
Activation Hook
You can use register_activation_hook() function to set up an activation hook.
Just like this:
register_activation_hook(
__FILE__,
'function_to_run'
);
Deactivation Hook
You can use register_deactivation_hook() function to set up an activation hook.
Just like this:
register_deactivation_hook(
__FILE__,
'function_to_run'
);
The ‘__FILE__’ refers to the main plugin file.
The main plugin file is the one with plugin header comment and usually you keep these two functions inside the main file.
What if the main file doesn’t have those functions?
You just need to change the first parameter in those functions and point it to where the main plugin file is.
Example form WordPress Developers
This activation hook refreshes permalinks and get rid of 404 errors when you register a custom post type.
The deactivation hook just reverses the process.
/**
* Register the "book" custom post type
*/
function pluginprefix_setup_post_type() {
register_post_type( 'book', ['public' => true ] );
}
add_action( 'init', 'pluginprefix_setup_post_type' );
/**
* Activate the plugin.
*/
function pluginprefix_activate() {
// Trigger our function that registers the custom post type plugin.
pluginprefix_setup_post_type();
// Clear the permalinks after the post type has been registered.
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
/**
* Deactivation hook.
*/
function pluginprefix_deactivate() {
// Unregister the post type, so the rules are no longer in memory.
unregister_post_type( 'book' );
// Clear the permalinks to remove our post type's rules from the database.
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );
activation examples hook plugin