Disabling plugin deactivation in WordPress

The problem came up recently about how to make sure plugins activated in the WordPress plugin UI don’t get deactivated if they are necessary for a site to function.  I thought that was an interesting thought puzzle worth spending 15 minutes on, so I came up with this function as a solution:

function dt_force_plugin_active( $plugin ) {
	add_filter( 'pre_update_option_active_plugins', function ( $active_plugins ) use ( $plugin ) {
		// Match if properly named: wp-plugin (wp-plugin/wp-plugin.php).
		$proper_plugin_name = $plugin . '/' . $plugin . '.php';

		if (
			file_exists( WP_PLUGIN_DIR . '/' . $proper_plugin_name )
			&& is_file( WP_PLUGIN_DIR . '/' . $proper_plugin_name )
			&& ! in_array( $proper_plugin_name, $active_plugins, true )
		) {
			$active_plugins[] = $proper_plugin_name;
			return array_unique( $active_plugins );
		}

		// Match if improperly named: wp-plugin/cool-plugin.php.
		if (
			file_exists( WP_PLUGIN_DIR . '/' . $plugin )
			&& is_file( WP_PLUGIN_DIR . '/' . $plugin )
			&& ! in_array( $plugin, $active_plugins, true )
		) {
			$active_plugins[] = $plugin;
			return array_unique( $active_plugins );
		}

		return array_unique( $active_plugins );
	}, 1000, 1 );
}

Which can be activated in your theme’s functions.php like so:

dt_force_plugin_active( 'akismet' ); or dt_force_plugin_active( 'wordpress-seo/wp-seo.php' );

The only downside that I’ve seen so far is that you still get the Plugin deactivated. message in the admin notices.

One thought on “Disabling plugin deactivation in WordPress

  1. Pingback: Securing WordPress Plugins | Derrick.Blarg

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s