Using WordPress ‘deactivate_blog’ PHP action

The deactivate_blog WordPress PHP action fires before a network site is deactivated, allowing you to execute custom code when this event occurs.

Usage

add_action('deactivate_blog', 'my_custom_function', 10, 1);

function my_custom_function($id) {
  // your custom code here
  return $id;
}

Parameters

  • $id (int) – The ID of the site being deactivated.

More information

See WordPress Developer Resources: deactivate_blog

Examples

Send an email when a site is deactivated

Send an email to the administrator when a site is deactivated.

add_action('deactivate_blog', 'send_email_on_deactivation', 10, 1);

function send_email_on_deactivation($id) {
  $admin_email = get_option('admin_email');
  $subject = 'Site Deactivated';
  $message = "Site with ID: $id has been deactivated.";
  wp_mail($admin_email, $subject, $message);
}

Log site deactivation

Log site deactivation events in a custom log file.

add_action('deactivate_blog', 'log_site_deactivation', 10, 1);

function log_site_deactivation($id) {
  $log_file = WP_CONTENT_DIR . '/deactivation_log.txt';
  $current_time = current_time('mysql');
  $log_entry = "Site ID: $id was deactivated on $current_time\n";
  file_put_contents($log_file, $log_entry, FILE_APPEND);
}

Unpublish all posts on deactivation

Unpublish all posts when a site is deactivated.

add_action('deactivate_blog', 'unpublish_posts_on_deactivation', 10, 1);

function unpublish_posts_on_deactivation($id) {
  switch_to_blog($id);
  $args = array('post_type' => 'post', 'post_status' => 'publish');
  $posts = get_posts($args);
  foreach ($posts as $post) {
    wp_update_post(array('ID' => $post->ID, 'post_status' => 'draft'));
  }
  restore_current_blog();
}

Disable user accounts on site deactivation

Disable all user accounts associated with the site when it is deactivated.

add_action('deactivate_blog', 'disable_users_on_deactivation', 10, 1);

function disable_users_on_deactivation($id) {
  switch_to_blog($id);
  $users = get_users();
  foreach ($users as $user) {
    update_user_meta($user->ID, 'account_disabled', true);
  }
  restore_current_blog();
}

Remove site-specific customizations

Remove site-specific customizations from the options table when the site is deactivated.

add_action('deactivate_blog', 'remove_customizations_on_deactivation', 10, 1);

function remove_customizations_on_deactivation($id) {
  switch_to_blog($id);
  delete_option('my_custom_theme_options');
  restore_current_blog();
}