Activation / Deactivation Hooks

Standard
[display-posts post_type="content" id="3672" include_content=true include_title=false wrapper="div" wrapper_class=""]

Activation / Deactivation Hooks

Activation and deactivation hooks provide ways to perform actions when plugins are activated or deactivated.

Plugins can run an installation routine when they are activated in order to add rewrite rules, add custom database tables, or set default option values. The deactivation hook is sometimes confused with the uninstall hook. The deactivation hook is best used to clear temporary data such as caches and temp directories.

To set up an activation hook, use the register_activation_hook() function:

1
register_activation_hook( __FILE__, 'pluginprefix_function_to_run' );

To set up a deactivation hook, use the similar register_deactivation_hook() function:

1
register_deactivation_hook( __FILE__, 'pluginprefix_function_to_run' );

The first parameter in each of these functions refers to your main plugin file, which is the file in which you have placed the plugin headers. Usually these two functions will be triggered from within the main plugin file; however, if the functions are placed in any other file, you must update the first parameter to correctly point to the main file.

One of the most common uses for an activation hook is to refresh WordPress permalinks when a plugin registers a custom post type. This gets rid of the nasty 404 errors. Let’s look at an example of how to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function pluginprefix_setup_post_type() {
 
    // Register our "book" custom post type
    register_post_type( 'book', array( 'public' => 'true' ) );
 
}
add_action( 'init', 'pluginprefix_setup_post_type' );
 
function pluginprefix_install() {
 
    // Trigger our function that registers the custom post type
    pluginprefix_setup_post_types();
 
    // Clear the permalinks after the post type has been registered
    flush_rewrite_rules();
 
}
register_activation_hook( __FILE__, 'pluginprefix_install' );

If you are unfamiliar with registering custom post types, don’t worry – this will be covered later. This example is used simply because it’s very commonplace.

Using the example from above, the following is how to reverse this process and deactivate a plugin:

1
2
3
4
5
6
7
8
9
function pluginprefix_deactivation() {
 
    // Our post type will be automatically removed, so no need to unregister it
 
    // Clear the permalinks to remove our post type's rules
    flush_rewrite_rules();
 
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivation' );

For further information regarding activation and deactivation hooks, here are some excellent resources:

 
Skip to toolbar