How to log and notify via email when a WordPress plugin is disabled or deleted?

Sometimes, you want to make sure that a specific esssential plugin is never deleted on your WordPress website or at least you want to be notified when ever this happens.

Imagine you have a tax plugin that calculates the tax in your WooCommerce or Easy Digital Downloads shop system. If this plugin is disabled for a reason, all your purchase prices will be miscalculated and it can take a while until you recognize that.

There is no 100% protection to prevent a plugin from being disabled on your WordPress website, but when it happens, you can copy the following code into a mu-plugin like plugin-logger.php and add it to the folder wp-content/mu-plugins

PHP
<?php

/*
 * Plugin Name: Log deleted plugins by WP Staging
 * Plugin URI: https://wp-staging.com
 * Description: Write a log file whenever a plugin is deleted or deactivated plugins.
 *
 * This is a must-use standalone plugin.
 *
 * Author: WP Staging
 * Version: 1.0
 * Author URI: https://wp-staging.com
 */

add_action('deactivated_plugin', function ($plugin_file) {

    $datetime = date('d-m-Y H:i:s');

    $message = "[{$datetime}] Deactivated plugin {$plugin_file}";

    error_log(
        "$message\n",
        3,
        WP_CONTENT_DIR . "/7263767234-deleted-plugins.log"
    );

    wp_mail('youremailaddress@example.com', 'Plugin deactivated on example.com', $message);

}, 20, 2);

add_action('deleted_plugin', function ($plugin_file, $deleted) {

    if ($deleted) {

        $datetime = date('d-m-Y H:i:s');

        $message = "[{$datetime}] Deleted plugin {$plugin_file}";

        error_log(
            "[{$datetime}] Deleted plugin {$plugin_file}\n",
            3,
            WP_CONTENT_DIR . "/7263767234-deleted-plugins.log"
        );

        wp_mail('youremailaddress@example.com', 'Plugin deleted on example.com', $message);
    }

}, 20, 2);

Once any of the installed plugins is either disabled or deleted by the WordPress hooks deleted_plugin or deactivated_plugin you will get an email notification. It will also log the report in the file wp-content//7263767234-deleted-plugins.log.

I recommend to adjust the path and file name for security purposes.