Activation and Deactivation of a Plugin

Writing a plugin is great and all, since it will run code all the time affecting how WordPress operates.

But sometimes you want things to happen during activation and deactivation of the plugin. For some plugins, this is necessary (in the case of DisableMU, it is actually the only time that something occurs since the plugin is completely passive the rest of the time). For other plugins, it is simply a convenient time to do something.

register_activation_hook( __FILE__, 'myPlugin_activate' );
register_deactivation_hook( __FILE__, 'myPlugin_deactivate' );

function myPlugin_activate() {
    // Do activation stuff here

function myPlugin_deactivate() {
    // Do deactivation stuff here

These calls are very straightforward, each one only taking 2 parameters. The first variable is the path to your plugin’s base file, which for the purposes of the example above we’re just assuming is the working file in a simple one-file plugin. The second variable, like most other hooks, is the name of the function that should run when this condition is met. So when register_activation_hook() triggers during your plugin’s activation, it will run whatever you have inside the myPlugin_activate() function.

What you put in these functions is your choice. Add some validation code, initialize values in the Options table for your plugin to reference later: the possibilities are really up to you.

Remember that the deactivation part of the process is especially important. More often than not, you should use the deactivation¬†function to clean up after yourself, and not leave any traces behind on the WordPress installation that was running your plugin. You may shoot yourself in the foot doing this (you don’t want a user to have to set your entire plugin’s complicated options settings again just because they deactivated and re-activated your plugin) but there are still many valid times when it makes sense to “sweep up” during this phase.

Good luck, and happy coding!

Leave a Reply