Ideal Postcodes is an address lookup service that allows you to autocomplete addresses based on part of the address or a postcode.
In this tutorial, I’ll show you how to apply it to the standard address field in Gravity Forms.
In this tutorial, I’ll show you how to apply it to the standard address field in Gravity Forms.
First things first, you’ll need to sign up for an account with Ideal Postcodes and get an API key which we’ll use in the code below.
Then on your form, add an address field and in the Appearance options add the class ideal-postcodes-address-field to the “Custom CSS Class” field. This will allow us to target just this field in the code.
The code that you need to add to your WordPress theme’s functions.php is as follows:
add_filter('gform_field_content', 'add_ideal_postcodes_to_address_field', 10, 5); function add_ideal_postcodes_to_address_field($content, $field, $value, $lead_id, $form_id) { if($field->cssClass == 'ideal-postcodes-address-field' && RG_CURRENT_VIEW != 'entry') { $ideal_postcodes_address_field_code = ' <script src="https://cdn.jsdelivr.net/npm/@ideal-postcodes/address-finder-bundled@4"></script> <script> IdealPostcodes.AddressFinder.setup({ apiKey: "XXXYYYZZZ", outputFields: { line_1: "#input_'.$form_id.'_'.$field->id.'_1", line_2: "#input_'.$form_id.'_'.$field->id.'_2", county: "#input_'.$form_id.'_'.$field->id.'_4", post_town: "#input_'.$form_id.'_'.$field->id.'_3", postcode: "#input_'.$form_id.'_'.$field->id.'_5", country: "#input_'.$form_id.'_'.$field->id.'_6", }, }); </script> '; $content = $content.$ideal_postcodes_address_field_code; } return $content; }
The Ideal Postcodes functionality comes from some JavaScript code that they provide. So we’ll just add this to the field by hooking into the Gravity Forms filter gform_field_content and creating our own function add_ideal_postcodes_to_address_field.
We then add an if statement to check that the CSS class is ideal-postcodes-address-field and the current view isn’t the entry view.
The Ideal Postcodes JS script is included and we add some JS code to marry up the various fields on the form.
You’ll need to ensure that you add your API key where it has XXXYYYZZZ otherwise the code won’t work.
We then add the JS into the $content variable which is what gets returned from the function.