Using WordPress ‘activated_plugin’ PHP function

The activate_plugin() WordPress PHP function attempts to activate a plugin in a “sandbox” and redirects on success. It won’t try to activate an already activated plugin.

Usage

$result = activate_plugin($plugin, $redirect, $network_wide, $silent);
// your custom code here
return $result;

Parameters

  • $plugin (string) – Required. Path to the plugin file relative to the plugins directory.
  • $redirect (string) – Optional. URL to redirect to. Default: ''
  • $network_wide (bool) – Optional. Whether to enable the plugin for all sites in the network or just the current site. Multisite only. Default: false
  • $silent (bool) – Optional. Whether to prevent calling activation hooks. Default: false

More information

See WordPress Developer Resources: activate_plugin()

Examples

Activate a plugin

Activate a plugin by providing its relative path to the plugins directory:

$result = activate_plugin('my-plugin/my-plugin.php');

Activate a plugin and redirect

Activate a plugin and redirect the user to a specific URL after activation:

$result = activate_plugin('my-plugin/my-plugin.php', '/wp-admin/plugins.php');

Network-wide activation (Multisite)

Activate a plugin for all sites in a multisite network:

$result = activate_plugin('my-plugin/my-plugin.php', '', true);

Activate a plugin silently

Activate a plugin without calling its activation hooks:

$result = activate_plugin('my-plugin/my-plugin.php', '', false, true);

Check for activation errors

Check if the plugin activation encountered any errors:

$result = activate_plugin('my-plugin/my-plugin.php');
if (is_wp_error($result)) {
    // Handle error
}