The activated_plugin
hook in WordPress is an action hook that triggers immediately after a plugin is activated. This hook is particularly useful when you need to execute specific actions (like setting up options, creating custom database tables, or sending notifications) once a plugin is successfully activated.
Hook Name
activated_plugin
Hook Type
Action Hook
Parameters
The activated_plugin
hook accepts two parameters:
- $plugin (string): The path to the plugin file relative to the
plugins
directory.
Example:my-plugin/my-plugin.php
- $network_wide (bool): Whether the plugin is activated network-wide for all sites in a multisite network. Default is
false
.
Usage Example
Below is an example of how to use the activated_plugin
hook to perform an action (e.g., logging the activation of a plugin).
Basic Example
Real-Life Example: Create Database Table on Plugin Activation
When you activate a plugin, you might need to set up a custom database table. The example below shows how you can achieve that using the activated_plugin
hook.
Full Example: Redirect After Plugin Activation
The following code snippet demonstrates how to redirect the admin to the plugin’s settings page after activation.
WordPress Version History for activated_plugin
The activated_plugin
hook was added to WordPress in version 2.9. Since its introduction, it has remained stable, and no major changes have been made to its functionality in subsequent WordPress versions.
Key Notes
- Priority and Arguments:
You can set the priority of the hook (default is 10) and use the$plugin
and$network_wide
parameters to customize your actions. - Multisite Considerations:
If you’re building a plugin for a multisite setup, you can use the$network_wide
parameter to determine whether the plugin is being activated for the entire network. - Avoid Plugin Conflicts:
Be sure to check the$plugin
parameter to ensure your code runs only for your plugin.
Step-by-Step Tutorial
Step 1: Identify Your Plugin Path
Find the path to your plugin file relative to the wp-content/plugins
directory. For example:
my-plugin/my-plugin.php
Step 2: Add the Hook to Your Plugin
In your main plugin file (e.g., my-plugin.php
), use the activated_plugin
hook as shown above.
Step 3: Perform Actions
Decide what actions you want to perform on activation:
- Redirect to a settings page.
- Log the activation.
- Create database tables or add default options.
Step 4: Test
Activate the plugin from the WordPress admin area and ensure the action is triggered. You can log or debug the hook to verify.
Example Image
Below is an image showing how the activated_plugin
hook is logged in WordPress:
By leveraging the activated_plugin
hook, you can ensure that your plugin is initialized properly after activation, enhancing functionality and providing a seamless experience for users.