Using WordPress ‘comment_duplicate_trigger’ PHP action

The comment_duplicate_trigger WordPress PHP action fires immediately after a duplicate comment is detected.

Usage

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

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

Parameters

  • $commentdata (array): Comment data.

More information

See WordPress Developer Resources: comment_duplicate_trigger

Examples

Preventing comment duplication

Prevent duplicate comments by displaying a custom message.

add_action('comment_duplicate_trigger', 'prevent_duplicate_comments', 10, 1);

function prevent_duplicate_comments($commentdata) {
  wp_die(__('Duplicate comments are not allowed.', 'your-text-domain'));
}

Logging duplicate comments

Log duplicate comments to a text file.

add_action('comment_duplicate_trigger', 'log_duplicate_comments', 10, 1);

function log_duplicate_comments($commentdata) {
  $log_message = 'Duplicate comment detected: ' . $commentdata['comment_content'] . PHP_EOL;
  error_log($log_message, 3, 'duplicates.log');
}

Send email notification for duplicate comments

Send an email to the site administrator when a duplicate comment is detected.

add_action('comment_duplicate_trigger', 'notify_admin_about_duplicate', 10, 1);

function notify_admin_about_duplicate($commentdata) {
  $to = get_option('admin_email');
  $subject = __('Duplicate comment detected', 'your-text-domain');
  $message = __('A duplicate comment was detected:', 'your-text-domain') . ' ' . $commentdata['comment_content'];
  wp_mail($to, $subject, $message);
}

Add a custom prefix to duplicate comments

Add a custom prefix to the content of duplicate comments before saving them.

add_action('comment_duplicate_trigger', 'add_duplicate_prefix', 10, 1);

function add_duplicate_prefix($commentdata) {
  $commentdata['comment_content'] = '[DUPLICATE] ' . $commentdata['comment_content'];
  return wp_new_comment($commentdata, true);
}

Store duplicate comments as drafts

Change the status of duplicate comments to ‘draft’ before saving them.

add_action('comment_duplicate_trigger', 'save_duplicate_as_draft', 10, 1);

function save_duplicate_as_draft($commentdata) {
  $commentdata['comment_approved'] = '0';
  return wp_new_comment($commentdata, true);
}