Admin & Dashboard PHP Intermediate

Stop Key Plugins Being Deactivated

Remove the Deactivate and Delete links for plugins your site depends on, and quietly keep them active if someone tries anyway.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 28 lines
function nahnu_locked_plugins(): array {
	return [
		'woocommerce/woocommerce.php',
		'nahnu-login-shield/nahnu-login-shield.php',
	];
}

// Hide Deactivate and Delete on the Plugins screen.
add_filter( 'plugin_action_links', function ( array $actions, string $plugin_file ): array {
	if ( in_array( $plugin_file, nahnu_locked_plugins(), true ) ) {
		unset( $actions['deactivate'], $actions['delete'] );
		$actions['nahnu_locked'] = '<span style="color:#6B6680">Required by this site</span>';
	}
	return $actions;
}, 10, 2 );

// Keep them active if they're deactivated in bulk or by another tool.
add_filter( 'pre_update_option_active_plugins', function ( $new, $old ) {
	if ( defined( 'NAHNU_UNLOCK_PLUGINS' ) && NAHNU_UNLOCK_PLUGINS ) {
		return $new;
	}
	foreach ( nahnu_locked_plugins() as $plugin ) {
		if ( in_array( $plugin, (array) $old, true ) && ! in_array( $plugin, (array) $new, true ) && file_exists( WP_PLUGIN_DIR . '/' . $plugin ) ) {
			$new[] = $plugin;
		}
	}
	return $new;
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

On client sites, deactivating the wrong plugin, such as WooCommerce or a security plugin, can take the site down or open a hole. This snippet protects a short list of plugins from being switched off by accident.

How it works

The plugin_action_links filter removes the Deactivate and Delete links for the listed plugins and adds a “Required by this site” note.

The list of active plugins is stored in the active_plugins option. pre_update_option_active_plugins runs before it’s saved, and puts back any locked plugin that was removed, so bulk actions and other tools can’t switch them off either.

Things to watch

  • To make changes yourself, add define( 'NAHNU_UNLOCK_PLUGINS', true ); to wp-config.php temporarily.
  • If a locked plugin’s folder is deleted or renamed, the snippet lets WordPress deactivate it, so a missing plugin can’t cause errors.
  • Use the plugin’s main file path as shown in the Plugins list, such as folder/file.php.

How to test it

Open Plugins. WooCommerce should show “Required by this site” instead of Deactivate. Try a bulk deactivate: it should stay active.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only