Function Documentation

WordPress Function Documentation Progress

Writing Plugins: Activation and Deactivation

WordPress provides hooks for when the plugin is activated and deactivated. Some plugins will have logic in their init function which check to see if set up or installed itself and if it didn’t it would install or upgrade itself.

The upgrader check can still remain in the init function, a user might have not deactivated the plugin before uploading the new files. The installer can be placed in the activation hook which can check if the plugin had been installed and install if it hadn’t installed already. It can also check to see if it needs to upgrade, in case the user deactivated before uploading the new plugin files or had the plugin deactivated for some other reason.

Any amount of code for which can be moved to the activation and deactivation functions from the init function can save that much overhead and reduce the complexity of the init process.


function myplugin_activation() {
    $pluginOptions = get_option('myplugin_data');

    if ( false === $pluginOptions ) {
        // Install plugin
    } else if ( MYPLUGIN_VER != $pluginOptions['version'] ) {
        // Upgrade plugin

register_activation_hook(__FILE__, 'myplugin_activation');

It is really that easy. WordPress provides a convenience function for hooking into the plugin’s activation hook, no matter where the plugin is located. If your plugin is moved from its directory structure, then if you manually hooked into the activation action, you might not be hooking into the right one. There is a way around that problem, but it is easier to just use register_activation_hook() instead.


The deactivation is easier, but most plugins don’t need it. You can be annoying and prevent the user from disabling your plugin, but they’ll get wise to your deception and remove your plugin, if you choose to do that. It would be unwise to include anything in your plugin that might discourage further usage and users.

It will be useful if you wish to include an uninstaller, in case your plugin creates new tables or adds options or whatever else that may need to be cleaned up. The topic of building an uninstaller is for another day, right now, it is one idea in case you have other needs or ideas for it.

function myplugin_deactivation() {
    $pluginOptions = get_option('myplugin_data');

    if ( true === $pluginOptions['uninstall'] ) {

register_deactivation_hook(__FILE__, 'myplugin_deactivation');

Again, WordPress provides another convenience function for the deactivation of your plugin. The logic for the deactivation is a lot less than the activation in most cases.


January 8, 2008 Posted by | Writing Plugins Series | , , , | Leave a comment