Skip to content
Clear Postcode

Integration · No-code

UK postcode check for WordPress forms

A 20-line script checks the postcode field of any WordPress form as the visitor types and shows a tick or a gentle hint. It uses a publishable key locked to your domain, so it's safe in the page.

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

Set it up

  1. 1Create a publishable key (cp_pub_) in your dashboard and add your domain to it.
  2. 2Give your form's postcode field the CSS class cp-postcode.
  3. 3Add the script in a Custom HTML block or your footer (WPCode or similar); replace YOUR_PUBLISHABLE_KEY.

The code

<script>
document.querySelectorAll(".cp-postcode input, input.cp-postcode").forEach((el) => {
  const note = document.createElement("small");
  el.after(note);
  let t;
  el.addEventListener("input", () => {
    clearTimeout(t);
    t = setTimeout(async () => {
      const pc = el.value.trim();
      if (pc.length < 5) return (note.textContent = "");
      const r = await fetch("https://api.clearpostcode.co.uk/v1/postcodes/" + encodeURIComponent(pc) + "/validate", { headers: { "x-api-key": "YOUR_PUBLISHABLE_KEY" } });
      const d = (await r.json()).data;
      note.textContent = !d ? "" : d.valid ? "✓ " + d.postcode : d.replaced_by ? "That postcode has changed: try " + d.replaced_by : d.format_valid ? "We can't find that postcode: please check it" : "UK postcodes look like SW1A 1AA";
    }, 400);
  });
});
</script>

Questions

WordPress forms questions

Does each keystroke cost a lookup?

No. The script waits until typing pauses, and you're only charged when a postcode is found.