Using WordPress ‘clean_comment_cache’ PHP action

The clean_comment_cache WordPress PHP action fires immediately after a comment has been removed from the object cache.

Usage

add_action('clean_comment_cache', 'your_custom_function', 10, 1);

function your_custom_function($comment_id) {
    // your custom code here
}

Parameters

  • $comment_id (int) – The Comment ID.

More information

See WordPress Developer Resources: clean_comment_cache

Examples

Log Cache Cleaning

Log when a comment cache is cleaned:

add_action('clean_comment_cache', 'log_comment_cache_clean', 10, 1);

function log_comment_cache_clean($comment_id) {
    error_log("Comment cache cleaned for comment ID: {$comment_id}");
}

Custom Cache Deletion

Delete a custom cache related to the comment:

add_action('clean_comment_cache', 'delete_custom_comment_cache', 10, 1);

function delete_custom_comment_cache($comment_id) {
    wp_cache_delete("custom_comment_{$comment_id}", 'custom_comment_group');
}

Update Comment Count

Update the comment count for the related post:

add_action('clean_comment_cache', 'update_post_comment_count', 10, 1);

function update_post_comment_count($comment_id) {
    $comment = get_comment($comment_id);
    $post_id = $comment->comment_post_ID;
    wp_update_comment_count($post_id);
}

Notify Admin

Send a notification to the admin when a comment cache is cleaned:

add_action('clean_comment_cache', 'notify_admin_comment_cache_clean', 10, 1);

function notify_admin_comment_cache_clean($comment_id) {
    $admin_email = get_option('admin_email');
    $subject = "Comment Cache Cleaned: {$comment_id}";
    $message = "The cache for comment ID {$comment_id} has been cleaned.";
    wp_mail($admin_email, $subject, $message);
}

Clear a transient related to the comment:

add_action('clean_comment_cache', 'clear_related_transient', 10, 1);

function clear_related_transient($comment_id) {
    delete_transient("related_comments_{$comment_id}");
}