Using WordPress ‘register_activation_hook()’ PHP function

The register_activation_hook() WordPress PHP function sets the activation hook for a plugin, which is called when the plugin is activated.

Usage

register_activation_hook( $file, $callback );

Parameters

  • $file (string): The filename of the plugin, including the path.
  • $callback (callable): The function hooked to the ‘activate_PLUGIN’ action.

More information

See WordPress Developer Resources: register_activation_hook()

Examples

Basic plugin activation

When the plugin is activated, this code will create a new table in the database.

function create_plugin_database_table() {
    // Code to create a new table in the database
}

register_activation_hook( __FILE__, 'create_plugin_database_table' );

Singleton class pattern

For a plugin that uses the singleton class pattern, add the activation hook like this:

class MyPlugin {
    static function install() {
        // Code to run on plugin activation
    }
}

register_activation_hook( __FILE__, array( 'MyPlugin', 'install' ) );

Activation function in an additional file

If the activation function is in an additional file, register the activation function like this:

include_once dirname( __FILE__ ) . '/additional_file.php';

register_activation_hook( __FILE__, array( 'AdditionalClass', 'on_activate_function' ) );

Activation function inside a constructor

If the activation function is inside a constructor, register the activation function like this:

class MyPlugin {
    public function __construct() {
        register_activation_hook( __FILE__, array( 'MyPlugin', 'your_method_name' ) );
    }

    public static function your_method_name() {
        // Code to run on plugin activation
    }
}

new MyPlugin();

Activation function with a separate class

If the activation function is inside a separate class, register the activation function like this:

class MyPlugin {
    public function __construct() {
        register_activation_hook( __FILE__, array( $this, 'activate' ) );
    }

    public function activate() {
        // Code to run on plugin activation
    }
}

$obj = new MyPlugin();