Codex

Function Reference/register activation hook

Contents

Description

The function register_activation_hook (introduced in WordPress 2.0) registers a plugin function to be run when the plugin is activated.

This is easier than using the activate_pluginname action.

Usage

 <?php register_activation_hook($file$function); ?> 

Parameters

$file
(string) (required) Path to the main plugin file inside the wp-content/plugins directory. A full path will work.
Default: None
$function
(callback) (required) The function to be run when the plugin is activated. Any of PHP's callback pseudo-types will work.
Default: None

Examples

If you have a function called myplugin_activate() in the main plugin file at either

  • wp-content/plugins/myplugin.php or
  • wp-content/plugins/myplugin/myplugin.php

use this code:

register_activation_hook( __FILE__, 'myplugin_activate' );

This will call the myplugin_activate() function on activation of the plugin. This is a more reliable method than using the activate_pluginname action.

Notes

Related discussion with another sample of working code: http://wordpress.org/support/topic/312342

A Note on Variable Scope

If you're using global variables, you may find that the function you pass to register_activation_hook() does not have access to global variables at the point when it is called, even though you state their global scope within the function like this:

$myvar='whatever';

function myplugin_activate() {
  global $myvar;
  echo $myvar; // this will NOT be 'whatever'
}

register_activation_hook( __FILE__, 'myplugin_activate' );

This is because on that very first include, your plugin is NOT included within the global scope. It's included in the activate_plugin function, and so its "main body" is not automatically in the global scope.

This is why you should *always* be explicit. If you want a variable to be global, then you need to declare it as such, and that means anywhere and everywhere you use it. If you use it in the main body of the plugin, then you need to declare it global there too.

When activation occurs, your plugin is included from another function and then your myplugin_activate() is called from within that function (specifically, within the activate_plugin() function) at the point where your plugin is activated. The main body variables are therefore in the scope of the activate_plugin() function and are not global, unless you explicitly declare their global scope:

global $myvar;
$myvar='whatever';

function myplugin_activate() {
  global $myvar;
  echo $myvar; // this will be 'whatever'
}

register_activation_hook( __FILE__, 'myplugin_activate' );

More information on this is available here: http://wordpress.org/support/topic/201309

Related