Skip to content
ClearPostcode

Integration · E-commerce

UK postcode validation for WooCommerce

Add one PHP snippet to your theme's functions.php (or a snippets plugin) and WooCommerce checks every UK shipping postcode against the live data at checkout, asks the customer to correct a mistake and suggests the new postcode when an old one has been retired.

Get a free key10,000 lookups a month free · no card

Set it up

  1. 1Get a free secret key at /developers.
  2. 2Add the snippet with a code snippets plugin or in your child theme's functions.php; replace YOUR_KEY.
  3. 3Place a test order with ZZ1 1ZZ: checkout asks for a valid postcode.

The code

add_action('woocommerce_after_checkout_validation', function ($data, $errors) {
  $country = $data['shipping_country'] ?: $data['billing_country'];
  $pc = $data['shipping_postcode'] ?: $data['billing_postcode'];
  if ($country !== 'GB' || !$pc) return;
  $r = wp_remote_get('https://api.clearpostcode.co.uk/v1/postcodes/' . rawurlencode($pc) . '/validate', [
    'headers' => ['x-api-key' => 'YOUR_KEY'], 'timeout' => 3,
  ]);
  if (is_wp_error($r) || wp_remote_retrieve_response_code($r) !== 200) return; // never block on our outage
  $d = json_decode(wp_remote_retrieve_body($r), true)['data'] ?? null;
  if (!$d || $d['valid']) return;
  if (!$d['format_valid']) $errors->add('postcode', 'Please check your postcode: UK postcodes look like SW1A 1AA.');
  elseif (!empty($d['replaced_by'])) $errors->add('postcode', sprintf('That postcode has changed. Did you mean %s?', esc_html($d['replaced_by'])));
  // known: false with a valid format can be a brand-new build: let it through
}, 10, 2);

Questions

WooCommerce questions

Will it block new-build addresses?

No. A valid-format postcode we don't know yet goes through; only bad formats and retired postcodes get a message.

What if your API is down?

The snippet lets the order through on any error or timeout (3 seconds), so checkout never depends on us.