Activation Or Deactivation Hooks

Hooks for activation and deactivation provide you ways to do things when plugins are turned on or off.

Sometimes people mistake the deactivation hook for the uninstall hook. The uninstall hook works best for permanently erasing all data, including custom tables and plugin settings.

Activation Hook

Use the register_activation_hook() function to configure an activation hook:

register_activation_hook(
__FILE__,
‘pluginprefix_function_to_run’
);

Deactivation Hook

Use the register_deactivation_hook() function to configure an deactivation hook:

register_deactivation_hook(
__FILE__,
‘pluginprefix_function_to_run’
);

The primary plugin file, where the plugin header comment is located, is the file that is referenced by the first parameter in each of these functions. These two functions will often be called from the main plugin file; if they are in another file, you will need to change the first parameter to properly point to the main plugin file.

Example

/**
 * 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’ );

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top