WordPress Multisite: Disabling a network active plugin on a specific site

There are times where you have a multisite and need to have a plugin active on all but one (or a couple) of sites. One option here would be to activate the plugin on all the sites except the one that you need; but depending on the number of sites in the network this could take quite a while.

An alternative is to network activate the plugin, and specifically disable it on the site(s) that we don’t need it on. This can be achieved by hooking into the site_option_active_sitewide_plugins filter and removing the plugin(s) for the site(s) in question.

In this example, also available on Github Gist, we’re disabling the akismet/akismet.php and other/plugin.php plugins on sites 2, 3 and 5:

<?php

add_filter( 'site_option_active_sitewide_plugins',
	function( $value ) {

		// Lookup the current site object global
		$current_blog;

		// This would disable the plugins on sites with ID's 2, 3 and 5
		if ( in_array( $current_blog->blog_id, [ 2, 3, 5 ] ) ) {

			// Loop through each plugin that needs to be disabled
			foreach ( [ 'akismet/akismet.php', 'other/plugin.php' ] as $plugin ) {

				// Ensure the plugin is active, we can't disable it if it's not active..
				if ( array_key_exists( $plugin ) ) {
					unset( $value[ $plugin ] );
				}

			}

		}

	    return $value;
	},
10 ,1 );