Using WordPress ‘clean_comment_cache()’ PHP function

The clean_comment_cache() WordPress PHP function removes a comment from the object cache. It essentially clears the cache for a particular comment or a set of comments.

Usage

To use clean_comment_cache(), you need to pass the ID of the comment you want to remove from the cache. You can also pass an array of IDs if you need to remove multiple comments from the cache.

clean_comment_cache( $ids );

For instance, to remove the comment with ID 5 from the cache:

clean_comment_cache( 5 );

Parameters

  • $ids (int|array) – Required. The ID of the comment or an array of comment IDs to be removed from the cache.

More information

See WordPress Developer Resources: clean_comment_cache()

This function is not deprecated and is available in the latest versions of WordPress. The source code for the function can be found in wp-includes/comment.php.

Examples

Clearing the cache for a single comment

In this example, we’re clearing the cache for the comment with ID 10.

// Clear the cache for comment with ID 10
clean_comment_cache( 10 );

Clearing the cache for multiple comments

You can also clear the cache for multiple comments at once by passing an array of comment IDs. In the following example, we clear the cache for comments with IDs 12, 15, and 18.

// Clear the cache for comments with IDs 12, 15, and 18
clean_comment_cache( array( 12, 15, 18 ) );

Clearing the cache after deleting a comment

You might want to clear the cache right after deleting a comment to ensure the cache is updated.

$comment_id = 20;
wp_delete_comment( $comment_id, true );

// Clear the cache for the deleted comment
clean_comment_cache( $comment_id );

Clearing the cache for all comments on a post

If you’re moderating comments on a post and want to ensure your changes are reflected immediately, you can clear the cache for all comments on that post.

// Get all comments for a post
$comments = get_comments( array( 'post_id' => $post_id ) );

$comment_ids = wp_list_pluck( $comments, 'comment_ID' );

// Clear the cache for all comments on the post
clean_comment_cache( $comment_ids );

Clearing the cache when a comment status changes

You can hook into the transition_comment_status action to clear the cache whenever a comment’s status changes.

function myplugin_transition_comment_status( $new_status, $old_status, $comment ) {
    // Clear the cache for the comment
    clean_comment_cache( $comment->comment_ID );
}
add_action( 'transition_comment_status', 'myplugin_transition_comment_status', 10, 3 );