The activate_{$plugin} WordPress PHP action fires as a specific plugin is being activated. This hook is used internally by register_activation_hook(). The dynamic portion of the hook name, $plugin, refers to the plugin basename. If a plugin is silently activated (such as during an update), this hook does not fire.
Usage
add_action('activate_your-plugin/your-plugin.php', 'your_custom_function');
function your_custom_function() {
// your custom code here
}
Parameters
$network_wide(bool) – Whether to enable the plugin for all sites in the network or just the current site. Multisite only. Default is false.
More information
See WordPress Developer Resources: activate_{$plugin}
Examples
Creating a Custom Post Type on Plugin Activation
This code creates a custom post type called “movies” when the plugin is activated.
add_action('activate_your-plugin/your-plugin.php', 'create_movies_post_type');
function create_movies_post_type() {
// Register a custom post type called 'movies'
register_post_type('movies', [
'public' => true,
'label' => 'Movies',
]);
}
Adding Custom Capabilities to a Role
This code adds custom capabilities to the “editor” role when the plugin is activated.
add_action('activate_your-plugin/your-plugin.php', 'add_custom_caps_to_editor_role');
function add_custom_caps_to_editor_role() {
// Get the 'editor' role
$editor_role = get_role('editor');
// Add custom capabilities
$editor_role->add_cap('manage_custom_plugin_settings');
}
Creating a Custom Database Table
This code creates a custom database table called “wp_movies” when the plugin is activated.
add_action('activate_your-plugin/your-plugin.php', 'create_movies_table');
function create_movies_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'movies';
// SQL to create the table
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
title varchar(255) NOT NULL,
PRIMARY KEY (id)
);";
// Execute the SQL query
$wpdb->query($sql);
}
Creating a Custom Page
This code creates a custom page called “Plugin Settings” when the plugin is activated.
add_action('activate_your-plugin/your-plugin.php', 'create_plugin_settings_page');
function create_plugin_settings_page() {
// Create a new page called 'Plugin Settings'
wp_insert_post([
'post_title' => 'Plugin Settings',
'post_content' => '[plugin_settings]',
'post_status' => 'publish',
'post_type' => 'page',
]);
}
Adding a Custom Option
This code adds a custom option called “plugin_option” with the default value “Hello World!” when the plugin is activated.
add_action('activate_your-plugin/your-plugin.php', 'add_custom_plugin_option');
function add_custom_plugin_option() {
// Add a custom option called 'plugin_option'
add_option('plugin_option', 'Hello World!');
}