Using WordPress ‘delete_blog’ PHP action

The delete_blog WordPress PHP action fires before a site is deleted.

Usage

add_action('delete_blog', 'my_custom_delete_blog_function', 10, 2);

function my_custom_delete_blog_function($site_id, $drop) {
    // your custom code here
}

Parameters

  • $site_id (int): The site ID.
  • $drop (bool): True if the site’s table should be dropped. Default false.

More information

See WordPress Developer Resources: delete_blog

Examples

Log site deletion

Log the deletion of a site in a custom log file.

function log_site_deletion($site_id, $drop) {
    $log_message = "Site ID {$site_id} was deleted.";
    error_log($log_message, 3, "/var/www/html/site_deletion.log");
}
add_action('delete_blog', 'log_site_deletion', 10, 2);

Send email notification

Send an email notification to the administrator when a site is deleted.

function notify_admin_on_site_deletion($site_id, $drop) {
    $admin_email = get_option('admin_email');
    $subject = "A site was deleted";
    $message = "Site ID {$site_id} was deleted.";
    wp_mail($admin_email, $subject, $message);
}
add_action('delete_blog', 'notify_admin_on_site_deletion', 10, 2);

Remove site’s uploaded files

Remove the uploaded files of the deleted site.

function remove_site_uploads($site_id, $drop) {
    $upload_dir = wp_upload_dir();
    $site_upload_dir = $upload_dir['basedir'] . "/sites/{$site_id}";
    if (file_exists($site_upload_dir)) {
        // Delete the site's upload directory
        rmdir($site_upload_dir);
    }
}
add_action('delete_blog', 'remove_site_uploads', 10, 2);

Remove site’s cache

Remove the cache related to the deleted site.

function clear_site_cache($site_id, $drop) {
    if (function_exists('wp_cache_delete_site')) {
        wp_cache_delete_site($site_id);
    }
}
add_action('delete_blog', 'clear_site_cache', 10, 2);

Add a custom event to Google Analytics

Track site deletion events in Google Analytics.

function track_site_deletion_event($site_id, $drop) {
    // Replace with your Google Analytics tracking code
    $tracking_code = "UA-12345678-1";

    $site_url = get_site_url($site_id);

    // Send the event to Google Analytics
    $event_data = array(
        'v' => '1',
        'tid' => $tracking_code,
        'cid' => mt_rand(100000, 999999),
        't' => 'event',
        'ec' => 'site_management',
        'ea' => 'site_deleted',
        'el' => $site_url,
    );
    $url = 'https://www.google-analytics.com/collect';
    wp_remote_post($url, array('body' => $event_data));
}
add_action('delete_blog', 'track_site_deletion_event', 10, 2);