Adding Custom Form Fields

In Age Gate v2 you can add custom fields to the challenge form. The following steps show how this is achieved.

Adding a form field

To add a form field, you need to hook either the pre_age_gate_custom_fields or post_age_gate_custom_fields  filters. These will add your fields before and after the standard fields respectively.

Let’s start by adding a simple field:

add_filter('post_age_gate_custom_fields', 'my_custom_fields', 10, 1);

function my_custom_fields($fields){
  $fields .= '<label><input type="checkbox" name="ag_field_terms" value="1" /> I accept the terms and conditions</label>';
  return $fields;
}

This will add a checkbox after the standard fields. The $fields parameter is passing any other fields from any previously defined hooks. It is important to append to and return the $fields variable to ensure no other fields are lost.

Validating a custom form field

In the above example, we want to enforce that the user has ticked the box. A simple solution would be to add a required HTML attribute to the field itself. However as we don’t know if the user’s browser supports the validation API, it’s best to also add some server side validation.

For this, we use the age_gate_validation filter.

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

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

As before, we receive the previously defined rules, and merge our new rule into it. The field will now be required, however, it will not output an error if it fails. For that, the original filter needs a minor change.

function my_custom_fields($fields){
  $fields .= '<label><input type="checkbox" name="ag_field_terms" value="1" /> I accept the terms and conditions</label>';
  $fields .= age_gate_error('ag_field_terms');
  return $fields;
}

The age_gate_error helper function takes the name of your form field and outputs the error if one occurs.

We now have a validation rule running on our custom input but it’s error message reads “The Ag Field Terms field is required” which isn’t great for our users.

Setting the display name of a custom field

There is one last set to get our field perfect, hooking into the age_gate_field_names filter.

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

function my_field_names($names){
  return array_merge($names, [
    'ag_field_terms' => "terms and conditions"
  ]);
}

Now the error message will read “The terms and conditions field is required

 

Gotchas and nuances

There are a couple of nuances to remember when adding custom for fields around the naming of fields:

Custom field names may not include age_gate in their name.

If you use array inputs, Age Gate will flatten them. The flattened reference should be used in helper functions and filters. For example my_custom_field[terms] becomes my_custom_field_terms