Using WordPress ‘pre_comment_approved’ PHP filter

pre_comment_approved is a WordPress PHP filter that lets you modify a comment’s approval status before it’s set in the database.

Usage

add_filter('pre_comment_approved', 'your_custom_function', 10, 2);
function your_custom_function($approved, $commentdata) {
    // your custom code here
    return $approved;
}

Parameters

  • $approved (int|string|WP_Error) – The approval status. Accepts 1 (approved), 0 (pending), ‘spam’, ‘trash’, or WP_Error.
  • $commentdata (array) – An array containing comment data.

More information

See WordPress Developer Resources: pre_comment_approved

Examples

Automatically approve comments from a specific email

Automatically approve comments from an email address you trust.

add_filter('pre_comment_approved', 'auto_approve_specific_email', 10, 2);
function auto_approve_specific_email($approved, $commentdata) {
    if ($commentdata['comment_author_email'] == '[email protected]') {
        return 1;
    }
    return $approved;
}

Reject comments containing specific words

Reject comments that contain specific words and send them to the trash.

add_filter('pre_comment_approved', 'reject_specific_words', 10, 2);
function reject_specific_words($approved, $commentdata) {
    $bad_words = array('spamword1', 'spamword2', 'spamword3');
    foreach ($bad_words as $word) {
        if (stripos($commentdata['comment_content'], $word) !== false) {
            return 'trash';
        }
    }
    return $approved;
}

Mark short comments as spam

Mark comments shorter than a specific length as spam.

add_filter('pre_comment_approved', 'short_comments_as_spam', 10, 2);
function short_comments_as_spam($approved, $commentdata) {
    if (strlen($commentdata['comment_content']) < 50) {
        return 'spam';
    }
    return $approved;
}

Set all comments as pending

Set all new comments to pending approval status.

add_filter('pre_comment_approved', 'set_all_comments_pending', 10, 2);
function set_all_comments_pending($approved, $commentdata) {
    return 0;
}

Disallow comments that contain any links and send them to the trash.

add_filter('pre_comment_approved', 'disallow_comments_with_links', 10, 2);
function disallow_comments_with_links($approved, $commentdata) {
    if (preg_match('/(http|https):\/\/[^\s]+/', $commentdata['comment_content'])) {
        return 'trash';
    }
    return $approved;
}