WordPress comments have always been a primary target for spam. As long as your website has some traffic and the comment function is enabled, you will inevitably encounter the frustration of automated spam comments. While several plugins can add CAPTCHA fields to combat this, adding a heavy plugin for a single feature can sometimes negatively impact your site’s performance.
In this article, I will show you how to add a custom CAPTCHA field to the WordPress comment form. Specifically, we will add a “What year is it?” question, hoping that spam bots won’t be able to answer it correctly.
Step 1: Add a Custom Field to the Comment Form
To add a custom field to the WordPress comment form, we can use the comment_form_default_fields filter. This filter returns an array of form fields, allowing you to inject new ones. This method works for both classic and block themes.
The following code snippet adds a new field labeled “What year is it?”:
function wprs_add_captcha_comment_field( $fields ) {
$fields['captcha'] = sprintf(
'<p class="comment-form-captcha">%s %s</p>',
sprintf(
'<label for="comment-captcha">%s %s</label>',
__( 'What year is it?', 'text_domain' ),
wp_required_field_indicator()
),
'<input id="comment-captcha" name="captcha" size="30" type="text" required>'
);
return $fields;
}
add_filter( 'comment_form_default_fields', 'wprs_add_captcha_comment_field' );
After adding this code, refresh your site, and you should see the field appear in the comment form. If it doesn’t appear, your theme or a plugin might be overriding the core WordPress comment form functionality.
Step 2: Verify the Custom CAPTCHA on Submission
Once the field is in place, the next step is to validate the input when a user submits a comment. We can use the pre_comment_on_post hook to perform this validation before WordPress processes the comment.
Here is the code I use to verify the custom CAPTCHA field:
function wprs_verify_comment_captcha() {
if ( empty( $_POST['captcha'] ) || (int) date( 'Y' ) !== (int) sanitize_text_field( wp_unslash( $_POST['captcha'] ) ) ) {
wp_die(
'<p>' . __( '<strong>Verification failed:</strong> Do you know what year it is?', 'text_domain' ) . '</p>',
__( 'Verification Failed' ),
[
'response' => 200,
'back_link' => true,
]
);
}
}
add_action( 'pre_comment_on_post', 'wprs_verify_comment_captcha' );
This code checks if the user submitted the CAPTCHA field and whether the value matches the current year returned by the PHP date() function. If either check fails, wp_die() terminates execution and displays an error message.
Conclusion
As you can see, adding a custom CAPTCHA field to WordPress comments is simple and only requires a couple of functions. While premium services like Akismet are effective, they come with a cost, and many free anti-spam plugins are either bloated or rely on third-party services like reCAPTCHA. This custom approach provides a lightweight, effective alternative.
