Wordpress - How To Activate Plugins via Code?
This is how I did it in some web apps:
function run_activate_plugin( $plugin ) {
$current = get_option( 'active_plugins' );
$plugin = plugin_basename( trim( $plugin ) );
if ( !in_array( $plugin, $current ) ) {
$current[] = $plugin;
sort( $current );
do_action( 'activate_plugin', trim( $plugin ) );
update_option( 'active_plugins', $current );
do_action( 'activate_' . trim( $plugin ) );
do_action( 'activated_plugin', trim( $plugin) );
}
return null;
}
run_activate_plugin( 'akismet/akismet.php' );
Plugin activation process is coded to work with WP admin interface. It performs some checks to prevent enabling plugins with errors (loading such on start might break WP).
It is handled by activate_plugin()
function (source) which is documented as unusable elsewhere.
So if you want to activate plugin by code the goal itself is relatively easy - to change active_plugins
option to include that plugin. But you will have to re-create related activation hooks from scratch and will risk breaking site by activating without sandbox step.
Plugins are stored in an array in the 'active_plugins' option. The array contains the file path to each plugin that is active.
To activate a plugin you need to determine what it's path will be, then pass that path to activate_plugin($plugin_path)
.
This is easier said than done though, and (at least in 2.9) the core code does not make it easy.
Before you can activate_plugin() you need to include the plugin.php file from wp-admin/includes/. You should also check to make sure your plugin isn't already active. The result looks something like this (YMMV):
// Define the new plugin you want to activate
$plugin_path = '/path/to/your/new/plugin.php';
// Get already-active plugins
$active_plugins = get_option('active_plugins');
// Make sure your plugin isn't active
if (isset($active_plugins[$plugin_path]))
return;
// Include the plugin.php file so you have access to the activate_plugin() function
require_once(ABSPATH .'/wp-admin/includes/plugin.php');
// Activate your plugin
activate_plugin($plugin_path);
I use this on production in WP 2.9 and have not had any major issues but in my testing it had very unexpected results with WPMU, so beware using this on network installs.