Skip to content

Instantly share code, notes, and snippets.

@peteeveleigh
Created March 17, 2022 10:59
Show Gist options
  • Save peteeveleigh/1b15442fa8cc5045824ddcea87dc805b to your computer and use it in GitHub Desktop.
Save peteeveleigh/1b15442fa8cc5045824ddcea87dc805b to your computer and use it in GitHub Desktop.
Get outbound part of UK postcode using Twig (handy for Craft Commerce shipping rules)
{# These are the valid UK postcode formats
according to https://ideal-postcodes.co.uk/guides/uk-postcode-format #}
{% set zipCodes = [
'AA9A 9AA',
'A9A 9AA',
'A9 9AA',
'A99 9AA',
'AA9 9AA',
'AA99 9AA'
] %}
{% for zipCode in zipCodes %}
{# Normalise zipcode, remove spaces, make uppercase
Remove last 3 characters and return the remainder #}
{{ zipCode }} - {{ zipCode|replace({' ':''})|upper|slice(0,-3) }}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment