The deleted_comment WordPress PHP action fires immediately after a comment is deleted from the database.
Usage
add_action('deleted_comment', 'your_custom_function', 10, 2);
function your_custom_function($comment_id, $comment) {
// your custom code here
}
Parameters
$comment_id(string) – The comment ID as a numeric string.$comment(WP_Comment) – The deleted comment object.
More information
See WordPress Developer Resources: deleted_comment
Examples
Log comment deletion
Log the details of deleted comments to a custom log file.
add_action('deleted_comment', 'log_deleted_comment', 10, 2);
function log_deleted_comment($comment_id, $comment) {
$log_message = "Comment ID: " . $comment_id . " - Author: " . $comment->comment_author . " - Deleted on: " . current_time('mysql') . "\n";
error_log($log_message, 3, "/path/to/your-log-file.log");
}
Send email notification
Send an email notification to the site administrator when a comment is deleted.
add_action('deleted_comment', 'send_email_on_comment_deletion', 10, 2);
function send_email_on_comment_deletion($comment_id, $comment) {
$admin_email = get_option('admin_email');
$subject = 'Comment Deleted';
$message = "A comment has been deleted.\n\nComment ID: " . $comment_id . "\nAuthor: " . $comment->comment_author;
wp_mail($admin_email, $subject, $message);
}
Update comment count
Update the custom comment count stored in a meta field when a comment is deleted.
add_action('deleted_comment', 'update_custom_comment_count', 10, 2);
function update_custom_comment_count($comment_id, $comment) {
$post_id = $comment->comment_post_ID;
$comment_count = get_post_meta($post_id, 'custom_comment_count', true);
$comment_count--;
update_post_meta($post_id, 'custom_comment_count', $comment_count);
}
Delete user’s comments
Delete all comments by a user when one of their comments is deleted.
add_action('deleted_comment', 'delete_all_users_comments', 10, 2);
function delete_all_users_comments($comment_id, $comment) {
$user_id = $comment->user_id;
$args = array(
'user_id' => $user_id,
'status' => 'all',
);
$comments = get_comments($args);
foreach ($comments as $user_comment) {
if ($user_comment->comment_ID != $comment_id) {
wp_delete_comment($user_comment->comment_ID, true);
}
}
}
Add a custom action
Run a custom action when a comment is deleted.
add_action('deleted_comment', 'run_custom_action', 10, 2);
function run_custom_action($comment_id, $comment) {
// your custom action here
}