Using WordPress ‘clean_term_cache’ PHP action

The clean_term_cache WordPress PHP action fires once after each taxonomy’s term cache has been cleaned.

Usage

add_action('clean_term_cache', 'my_custom_function', 10, 3);
function my_custom_function($ids, $taxonomy, $clean_taxonomy) {
    // your custom code here
}

Parameters

  • $ids (array): An array of term IDs.
  • $taxonomy (string): Taxonomy slug.
  • $clean_taxonomy (bool): Whether or not to clean taxonomy-wide caches.

More information

See WordPress Developer Resources: clean_term_cache

Examples

Log Term Cache Cleaning

Log when the term cache is cleaned for a specific taxonomy.

add_action('clean_term_cache', 'log_term_cache_cleaning', 10, 3);
function log_term_cache_cleaning($ids, $taxonomy, $clean_taxonomy) {
    if ($taxonomy === 'my_custom_taxonomy') {
        error_log('Term cache cleaned for custom taxonomy.');
    }
}

Clear Transient on Term Cache Cleaning

Clear a transient when the term cache is cleaned.

add_action('clean_term_cache', 'clear_transient_on_term_cache_clean', 10, 3);
function clear_transient_on_term_cache_clean($ids, $taxonomy, $clean_taxonomy) {
    delete_transient('my_custom_transient');
}

Custom Cache Cleanup for Custom Taxonomy

Perform custom cache cleanup for a custom taxonomy when the term cache is cleaned.

add_action('clean_term_cache', 'custom_cache_cleanup', 10, 3);
function custom_cache_cleanup($ids, $taxonomy, $clean_taxonomy) {
    if ($taxonomy === 'my_custom_taxonomy') {
        // Perform custom cache cleanup
    }
}

Update Post Count for Custom Taxonomy

Update the post count for a custom taxonomy when the term cache is cleaned.

add_action('clean_term_cache', 'update_post_count_for_custom_taxonomy', 10, 3);
function update_post_count_for_custom_taxonomy($ids, $taxonomy, $clean_taxonomy) {
    if ($taxonomy === 'my_custom_taxonomy') {
        // Update post count for custom taxonomy
    }
}

Notify Admin on Term Cache Cleaning

Send an email notification to the admin when the term cache is cleaned.

add_action('clean_term_cache', 'notify_admin_on_term_cache_clean', 10, 3);
function notify_admin_on_term_cache_clean($ids, $taxonomy, $clean_taxonomy) {
    $to = get_option('admin_email');
    $subject = 'Term Cache Cleaned';
    $message = 'The term cache has been cleaned for the taxonomy: ' . $taxonomy;
    wp_mail($to, $subject, $message);
}