The comment_{$old_status}_to_{$new_status} WordPress PHP action fires when the comment status is in transition from one specific status to another. The dynamic portions of the hook name, $old_status, and $new_status, refer to the old and new comment statuses, respectively.
Usage
add_action('comment_{$old_status}_to_{$new_status}', 'your_custom_function', 10, 1); function your_custom_function($comment) { // your custom code here }
Parameters
- $comment (WP_Comment) – Comment object.
More information
See WordPress Developer Resources: comment_{$old_status}_to_{$new_status}
Examples
Notify admin when a comment is approved
Sends an email to the admin when a comment is approved.
add_action('comment_unapproved_to_approved', 'notify_admin_on_approved_comment', 10, 1); function notify_admin_on_approved_comment($comment) { // Prepare email content $subject = "A comment has been approved on your website"; $message = "A comment has been approved on your website.\n\n"; $message .= "Author: {$comment->comment_author}\n"; $message .= "Comment: {$comment->comment_content}\n"; // Send email to admin wp_mail(get_option('admin_email'), $subject, $message); }
Log spam comments
Logs the details of spam comments in a log file.
add_action('comment_approved_to_spam', 'log_spam_comments', 10, 1); function log_spam_comments($comment) { // Prepare log content $log = "Spam comment detected:\n"; $log .= "Author: {$comment->comment_author}\n"; $log .= "Comment: {$comment->comment_content}\n"; $log .= "-------------------------\n"; // Write log to file file_put_contents('spam_comments.log', $log, FILE_APPEND); }
Change comment author name
Changes the comment author name to “Anonymous” when the comment is marked as spam.
add_action('comment_approved_to_spam', 'change_author_name_on_spam', 10, 1); function change_author_name_on_spam($comment) { $comment->comment_author = 'Anonymous'; wp_update_comment((array) $comment); }
Notify author when comment is approved
Sends an email to the comment author when their comment is approved.
add_action('comment_unapproved_to_approved', 'notify_author_on_approved_comment', 10, 1); function notify_author_on_approved_comment($comment) { // Prepare email content $subject = "Your comment has been approved"; $message = "Your comment has been approved on our website.\n\n"; $message .= "Comment: {$comment->comment_content}\n"; // Send email to comment author wp_mail($comment->comment_author_email, $subject, $message); }
Redirect to custom page when comment is unapproved
Redirects the user to a custom page when their comment is marked as unapproved.
add_action('comment_approved_to_unapproved', 'redirect_on_unapproved_comment', 10, 1); function redirect_on_unapproved_comment($comment) { $redirect_url = home_url('/unapproved-comment/'); wp_redirect($redirect_url); exit; }