php Code for Comment Validator

Add this code on functions.php. And make human validation function when someone do comment on your post.

function validator_for_comments() {
$a = rand(1, 100);
$b = rand(1, 100);
$c = $a + $b;
echo '<p class="comment-form-math">';
echo '<label for="comment_math">' . __('What is ' . $a . ' + ' . $b . '?') . '</label>';
echo '<input type="text" name="comment_math" id="comment_math" required />';
echo '<input type="hidden" name="comment_math_answer" value="' . $c . '" />';
echo '</p>';
}
add_action('comment_form_after_fields', 'validator_for_comments');

function validate_comments($comment_data) {
$math = $_POST['comment_math'];
$answer = $_POST['comment_math_answer'];
$back_url = wp_get_referer();
if ($math != $answer) {
wp_die(__('Error: The math question was answered incorrectly or field is empty.' . '</br>' . '<a href="' . esc_url($back_url) . '">' . __('Go back') . '</a>'));
}
return $comment_data;
}
add_filter('preprocess_comment', 'validate_comments');

Watch Video