Using WordPress ‘allow_empty_comment’ PHP filter

The allow_empty_comment WordPress PHP filter allows you to control whether empty comments should be allowed or not. The default behavior is to not allow empty comments.

Usage

add_filter('allow_empty_comment', 'your_custom_function', 10, 2);

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

    return $allow_empty_comment;
}

Parameters

  • $allow_empty_comment (bool): Whether to allow empty comments. Default is false.
  • $commentdata (array): Array of comment data to be sent to wp_insert_comment().

More information

See WordPress Developer Resources: allow_empty_comment

Examples

Allow empty comments globally

Allow empty comments for all posts.

add_filter('allow_empty_comment', 'allow_empty_comments_globally', 10, 2);

function allow_empty_comments_globally($allow_empty_comment, $commentdata) {
    return true;
}

Disallow empty comments for specific post types

Disallow empty comments for a specific post type, e.g., ‘product’.

add_filter('allow_empty_comment', 'disallow_empty_comments_for_products', 10, 2);

function disallow_empty_comments_for_products($allow_empty_comment, $commentdata) {
    $post_id = $commentdata['comment_post_ID'];
    if (get_post_type($post_id) === 'product') {
        return false;
    }
    return $allow_empty_comment;
}

Allow empty comments for logged-in users

Allow empty comments only for logged-in users.

add_filter('allow_empty_comment', 'allow_empty_comments_for_logged_in_users', 10, 2);

function allow_empty_comments_for_logged_in_users($allow_empty_comment, $commentdata) {
    if (is_user_logged_in()) {
        return true;
    }
    return $allow_empty_comment;
}

Allow empty comments with a specific comment type

Allow empty comments only for a specific comment type, e.g., ‘review’.

add_filter('allow_empty_comment','allow_empty_comments_for_review_type', 10, 2);

function allow_empty_comments_for_review_type($allow_empty_comment, $commentdata) {
if ($commentdata['comment_type'] === 'review') {
return true;
}
return $allow_empty_comment;
}

Disallow empty comments containing specific keywords

Disallow empty comments containing specific keywords, e.g., ‘spam’ or ‘phishing’.

add_filter('allow_empty_comment', 'disallow_empty_comments_with_keywords', 10, 2);

function disallow_empty_comments_with_keywords($allow_empty_comment, $commentdata) {
    $blocked_keywords = array('spam', 'phishing');

    foreach ($blocked_keywords as $keyword) {
        if (stripos($commentdata['comment_content'], $keyword) !== false) {
            return false;
        }
    }
    return $allow_empty_comment;
}