Search Knowledge Base by Keyword

How to add CAPTCHA to a WordPress website form

You are here:

To add a CAPTCHA check with the CAPTCHA 4WP plugin plugin to a custom form on your WordPress website you need two components. First you need to add the user facing field, so the user has something to click/interact with etc, and then you need to handle the captcha failure or success in your forms data processing code.

In this article we explain how you can add a CAPTCHA check to any custom form on WordPress websites in just two steps. If you have created the form with a plugin such as Contact Form 7 or Gravity Forms, the CAPTCHA 4WP plugin has out of the box support for these and many other plugins. Refer to the knowledge base for more information.

Step 1: Displaying the CAPTCHA check

You can display the captcha field in your custom form using the following action:

do_action( 'c4wp_captcha_form_field' );

The below code is a simple example of a website form with the CAPTCHA check. Ideally the CAPTCHA check should be triggered right before the submit button.

<?php
/**
* Template Name: My Form with Captcha
*
*/
get_header();
?>

<form action="#" method="POST" class="comment-form">
<?php wp_nonce_field( 'my-action', 'my-nonce' ); ?>

<div>
<input id="mytextfield" type="text" name="mytextfield" />
</div>

<?php do_action( 'c4wp_captcha_form_field' ); ?>

<input id="submit" type="submit" name="my-submit-button" id="submit" class="submit" value="<?php esc_attr_e( 'Submit', 'text-domain' ); ?>" />
</form>

<?php
get_footer();

Step 2: Processing and verifying the CAPTCHA

Once you add the CAPTCHA check, in your forms data processing where you typically read and validate the $_POST fields you will need to retrieve the response from your captcha field using the function c4wp_verify_captcha().

Although how/what you want to do with your form’s data will always differ, you can see in this example based on the above form of how this would work by redirecting the user to a “failure” page if the CAPTCHA fails.

function a_demo_form() {
if ( ! isset( $_POST['my-submit-button'] ) || ! isset( $_POST['my-nonce'] ) ) {
return;
}

if ( ! wp_verify_nonce( $_POST['my-nonce'], 'my-action' ) ) {
return;
}

$mytextfield = intval( $_POST['mytextfield'] );
$url = wp_get_referer();

// Redirect to failure page is captcha fails
$response = c4wp_verify_captcha();
if ( ! $response ) {
$url = add_query_arg( 'fail', 1, wp_get_referer() );
}

wp_safe_redirect( $url );
exit();
}
add_action( 'template_redirect', 'a_demo_form' );

Other ways to handle the CAPTCHA results

CAPTCHA 4WPalways returns a positive or negative result. This allows you to handle what happens as you want. For example you may want to return a new WP_Error or such, however, always depending on your specific setup and requirements.