Attempts activation of plugin in a “sandbox” and redirects on success.

A plugin that is already activated will not attempt to be activated again.

The way it works is by setting the redirection to the error before trying to include the plugin file. If the plugin fails, then the redirection will not be overwritten with the success message. Also, the options will not be updated and the activation hook will not be called on plugin error.

It should be noted that in no way the below code will actually prevent errors within the file. The code should not be used elsewhere to replicate the “sandbox”, which uses redirection to work.


activate_plugin( $plugin, $redirect = '', $network_wide = false, $silent = false )
 (string) Path to the main plugin file from plugins directory.
 (string) Optional. URL to redirect to.
Default: ''
 (boolean) Optional. Whether to enable the plugin for all sites in the network or just the current site. Multisite only. Default false.
Default: false
 (boolean) Optional. Whether to prevent calling activation hooks. Default false.
Default: false


(WP_Error|null) WP_Error on invalid file or null on success.


function activate_plugin( $plugin, $redirect = '', $network_wide = false, $silent = false ) {
	$plugin = plugin_basename( trim( $plugin ) );

	if ( is_multisite() && ( $network_wide || is_network_only_plugin($plugin) ) ) {
		$network_wide = true;
		$current = get_site_option( 'active_sitewide_plugins', array() );
		$_GET['networkwide'] = 1; // Back compat for plugins looking for this value.
	} else {
		$current = get_option( 'active_plugins', array() );

	$valid = validate_plugin($plugin);
	if ( is_wp_error($valid) )
		return $valid;

	if ( ( $network_wide && ! isset( $current[ $plugin ] ) ) || ( ! $network_wide && ! in_array( $plugin, $current ) ) ) {
		if ( !empty($redirect) )
			wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error
		wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $plugin );
71 more lines...
WP Trac GitHub

Link here