WordPress LogoI recently had the need to programmatically activate and deactivate WordPress plugins from within a custom admin UI (theme). It took me quite a lot of digging to figure out exactly how, so I figured I’d share it here.

Note that this requires wp-admin/includes/plugin.php to be included if you’re not running from within WordPress.

function toggle_plugin() {

	// Full path to WordPress from the root
	$wordpress_path = '/full/path/to/wordpress/';

	// Absolute path to plugins dir
	$plugin_path = $wordpress_path.'wp-content/plugins/';

	// Absolute path to your specific plugin
	$my_plugin = $plugin_path.'my_plugin/my_plugin.php';

	// Check to see if plugin is already active
	if(is_plugin_active($my_plugin)) {

		// Deactivate plugin
		// Note that deactivate_plugins() will also take an
		// array of plugin paths as a parameter instead of
		// just a single string.
		deactivate_plugins($my_plugin);
	}
	else {

		// Activate plugin
		activate_plugin($my_plugin);
	}
}