Using WordPress ‘pre_delete_term’ PHP action

The pre_delete_term WordPress PHP action fires when deleting a term, before any modifications are made to posts or terms.

Usage

add_action('pre_delete_term', 'your_function_name', 10, 2);

function your_function_name($term, $taxonomy) {
  // your custom code here

  return $term;
}

Parameters

  • $term (int) – Term ID.
  • $taxonomy (string) – Taxonomy name.

More information

See WordPress Developer Resources: pre_delete_term

Examples

Log term deletion

Logs term deletion to a custom log file.

add_action('pre_delete_term', 'log_term_deletion', 10, 2);

function log_term_deletion($term, $taxonomy) {
  $log_message = "Term ID {$term} from taxonomy {$taxonomy} is being deleted.";
  error_log($log_message, 3, "/path/to/your/custom.log");

  return $term;
}

Prevent term deletion

Prevent term deletion for a specific taxonomy.

add_action('pre_delete_term', 'prevent_term_deletion', 10, 2);

function prevent_term_deletion($term, $taxonomy) {
  if ($taxonomy == 'restricted_taxonomy') {
    wp_die('You are not allowed to delete terms from this taxonomy.');
  }

  return $term;
}

Notify admin by email

Notify the admin by email when a term is deleted.

add_action('pre_delete_term', 'notify_admin_term_deletion', 10, 2);

function notify_admin_term_deletion($term, $taxonomy) {
  $subject = 'Term Deletion';
  $message = "Term ID {$term} from taxonomy {$taxonomy} is being deleted.";
  $admin_email = get_option('admin_email');

  wp_mail($admin_email, $subject, $message);

  return $term;
}

Update term count

Update the term count for a custom taxonomy before deletion.

add_action('pre_delete_term', 'update_term_count_before_deletion', 10, 2);

function update_term_count_before_deletion($term, $taxonomy) {
  if ($taxonomy == 'custom_taxonomy') {
    $term_obj = get_term($term, $taxonomy);
    $term_count = $term_obj->count;
    update_option('custom_taxonomy_count', $term_count - 1);
  }

  return $term;
}

Delete associated metadata

Delete all associated metadata with a term before deletion.

add_action('pre_delete_term', 'delete_associated_metadata', 10, 2);

function delete_associated_metadata($term, $taxonomy) {
  delete_metadata('term', $term, '', '', true);

  return $term;
}