Using WordPress ‘delete_term’ PHP action

The delete_term WordPress PHP action fires after a term is deleted from the database and the cache is cleaned. It also has the ‘delete_$taxonomy’ hook available for targeting a specific taxonomy.

Usage

add_action('delete_term', 'my_custom_function', 10, 5);

function my_custom_function($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    // Your custom code here

    return $term;
}

Parameters

  • $term (int): Term ID.
  • $tt_id (int): Term taxonomy ID.
  • $taxonomy (string): Taxonomy slug.
  • $deleted_term (WP_Term): Copy of the already-deleted term.
  • $object_ids (array): List of term object IDs.

More information

See WordPress Developer Resources: delete_term

Examples

Log Deleted Terms

Keep track of deleted terms by logging them in a custom log file.

add_action('delete_term', 'log_deleted_terms', 10, 5);

function log_deleted_terms($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    $log = "Deleted Term: {$deleted_term->name} (ID: {$term}, Taxonomy: {$taxonomy})\n";
    error_log($log, 3, "/path/to/your/logfile.log");

    return $term;
}

Notify Admin on Term Deletion

Send an email notification to the admin when a term is deleted.

add_action('delete_term', 'notify_admin_term_deletion', 10, 5);

function notify_admin_term_deletion($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    $subject = "Term Deleted: {$deleted_term->name}";
    $message = "A term has been deleted from the {$taxonomy} taxonomy. Details:\n\nTerm Name: {$deleted_term->name}\nTerm ID: {$term}\nTaxonomy: {$taxonomy}";
    wp_mail(get_bloginfo('admin_email'), $subject, $message);

    return $term;
}

Remove Associated Posts on Term Deletion

Delete all posts associated with a deleted term.

add_action('delete_term', 'remove_associated_posts', 10, 5);

function remove_associated_posts($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    foreach ($object_ids as $post_id) {
        wp_delete_post($post_id, true);
    }

    return $term;
}

Clear Custom Cache on Term Deletion

Clear a custom cache when a term is deleted.

add_action('delete_term', 'clear_custom_cache', 10, 5);

function clear_custom_cache($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    // Replace 'my_custom_cache_key' with your actual cache key
    wp_cache_delete('my_custom_cache_key');

    return $term;
}

Redirect Deleted Term’s URL

Redirect the deleted term’s URL to the homepage.

add_action('delete_term', 'redirect_deleted_term_url', 10, 5);

function redirect_deleted_term_url($term, $tt_id, $taxonomy, $deleted_term, $object_ids) {
    $term_link = get_term_link($deleted_term);
    wp_redirect($term_link, 301);
    exit;

    return $term;
}