Advanced example

In this guide, we’ll be adding multiple fields that aren’t validated by default by Age Gate, ensure you have read the adding custom form fields section before this section.

We’ll be adding an email field before the main fields and a reCAPTCHA field after the form. For this example, a standard text input will be used for the email address to best demonstrate Age Gate validation.

As before, we start by adding a field. We’ll cover the email address first.

add_filter('pre_age_gate_custom_fields', 'my_custom_email', 10, 2);

function my_custom_email($fields){
  $fields .= '<label for="custom_email_input">Email Address</label>';
  $fields .= '<input type="text" name="custom_email_input" id="custom_email_input" placeholder="Enter an email address" value="'. age_gate_set_value('custom_email_input') .'" />';
  $fields .= age_gate_error('custom_email_input');
  return $fields;
}

Notice the use of the age_gate_set_value helper function. As with the age_gate_error helper it takes the key of the field. This will repopulate the form on failure.

Next, we’ll add a validation rule and readable field name for the email address

add_filter('age_gate_validation', 'my_validation_rules', 10, 1);

function my_validation_rules($rules){
  return array_merge($rules, [
    'custom_email_input' => 'required'
  ]);
}

add_filter('age_gate_field_names', 'my_field_names', 10, 1);

function my_field_names($names){
  return array_merge($names, [
    'custom_email_input' => "Email Address"
  ]);
}

The field is now required, but allows and content, not just a valid email. To fix this, we can pipe multiple validation rules together in the age_gate_validation filter:

function my_validation_rules($rules){
  return array_merge($rules, [
    'custom_email_input' => 'required|valid_email'
  ]);
}

The email address field will now be both required and a valid email address.

Adding the reCAPTHCA field

This time, we’ll add the field after the standard fields, so we’ll use the post_age_gate_custom_fields filter:

add_filter('post_age_gate_custom_fields', 'add_recaptcha_field', 10, 2);

function add_recaptcha_field($fields){
  $fields .= '<div class="g-recaptcha" id="recaptcha-age-gate" data-sitekey="YOURSITEKEY"></div>';
  return $fields;
}

Replace YOURSITEKEY with your own reCAPTCHA key and secret, if you don’t have one, you can get one from the reCAPTCHA website.

Next we need to add the reCAPTCHA JavaScript. Your site may already have this so skip this step if so.

add_action('wp_enqueue_scripts', 'enqueue_recaptcha');

function enqueue_recaptcha(){
  wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js?onload=recaptchaInit', array(), '', true );
}

Adding a custom validator for reCAPTCHA

Now we have our reCAPTCHA available, we need to be able to validate it. Well now hook into the age_gate_add_validators action to add a custom validator.

add_action('age_gate_add_validators', 'my_recaptcha_validation');

function my_recaptcha_validation(){
  Age_Gate_Validation::add_validator("recaptcha", function($field, $input, $param = NULL) {
    $url = 'https://www.google.com/recaptcha/api/siteverify';
  	$data = array(
  		'secret' => 'YOURSITESECRET',
  		'response' => $input[$field]
  	);
  	$options = array(
  		'http' => array (
  			'method' => 'POST',
  			'content' => http_build_query($data),
        'header'=> "Content-type: application/x-www-form-urlencoded\r\n",
  		)
  	);
  	$context  = stream_context_create($options);
  	$verify = file_get_contents($url, false, $context);
  	$captcha_success = json_decode($verify);
    return $captcha_success->success;
  });
}

This function adds a validation method called recaptcha to the Age Gate validation class. Again, you’ll need to replace YOURSITESECRET with your own.

Now we need to tell the validator to use this method. We can do this in the my_validation_rules function we defined earlier.

function my_validation_rules($rules){
  return array_merge($rules, [
    'custom_email_input' => 'required|valid_email',
    'g-recaptcha-response' => 'recaptcha'
  ]);
}

Note that g-recaptcha-response is just the name we are give by reCAPTCHA.

If we run our code, we’ll get an error on submission. This is because there is no error message for our validation method by default. We’ll need to use the age_gate_validation_messages filter to add a new one:

add_filter('age_gate_validation_messages', 'my_error_messages');
function my_error_messages($messages){
  return array_merge($messages, [
    'recaptcha' => 'The {field} is required'
  ]);
}

This work in the same way as previous filters where we receive an array of messages, merge ours in and return it. The {field} placeholder is where the field name will be injected. If your validation method accepts a parameter, that can be output using {param} as per the fields in Age Gate’s messages settings.

Note: This filter can also be used to override default messages, though they are prefixed with validate_ e.g. 'validate_required' => 'Your message here' .

The final step is to add a nice name for the error message, let’s update my_field_names.

function my_field_names($names){
  return array_merge($names, [
    'custom_email_input' => "Email Address",
    'g-recaptcha-response' => 'reCAPTCHA'
  ]);
}

We have now added a reCAPTCHA field to our Age Gate!

Gothchas

While the above should work in most cases, it’s possible under the JavaScript implementation that the reCAPTCHA does not exist when the page is rendered, especially if the is a hook on age_gate_restricted. In this scenario we will have to make a couple of adjustments to use ‘explicit’ rendering of the reCAPTCHA.

When we enqueued the JavaScript from Google, we just let it do the rendering for us. But we can also trigger that ourselves which serves our purpose here. Firstly, change the enqueue to:

wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js?amp;render=explicit', array(), '', true );

We are now telling the script not to render the reCAPTCHA by setting render to explicit.

Now we need to tell the reCAPTCHA to render only when the Age Gate is shown, for this we’ll add some JavaScript. This can go in the main theme’s JavaScript if available or a separate file can be enqueued:

$(document).on('agegateshown', function(){
	$('.g-recaptcha').each(function(i, el){
		var settings = $(el).data(),
				id = $(el).attr('id');

		grecaptcha.render(id, settings);
	});
});

Conclusion

These are just a couple of examples of how the form can be extended, there are fairly unlimited possibilities for adding your own fields.

Make sure you look at the available validators before creating you own as it may exist already, and look at the age_gate_form_{$status} action hook for details on how to handle the fields when the form submits