It is a common occurrence to receive requests for invoices that include a customer’s VAT for use with their country’s tax records. While WooCommerce does not ship with support for generating invoices, there are many great plugins which add invoice functionality.
Previously, when someone requested a VAT to be added, we simply directed the customer to cram it into the existing address fields – not anymore! As of today, we’ve added a special field to the billing address for entering a VAT which appears on invoices.
While building this functionality, it occurred to me, “Hey, this would make a great tutorial for other shop owners who need this.” So here you go; this is the exact process and code we used for our systems.
Step 1 – Adding a field to my account settings:
WooCommerce makes it trivially easy to add custom fields to the existing billing fields via the woocommerce_billing_fields
filter. You receive a keyed array of fields as the first argument which contain settings for each field. Doing a quick inspection will show you the various settings, but for this case we only need 3.
This will add a new optional field labeled “VAT” at the very bottom of the billing fields form.
WooCommerce will automatically save this field’s value to user meta when the settings are saved.
Step 2 – Add VAT to address formats:
WooCommerce renders various addresses include the billing address using what they call, “address formats.” Basically, these are templates for the layout of an address based on the country.
The templates use a fairly standard placeholder replacement approach for injecting values into the markup. While you could customize this by country, we opted to simply add the VAT to the end of each template by appending a {vat}
placeholder to every country.
This is made possible using the woocommerce_localisation_address_formats
filter which provides a keyed array of countries and their corresponding template.
Step 3 – Adding saved VAT to available address data:
Now we have a template waiting for the VAT but we need to provide the user data to WooCommerce function which merges the data with the template.
This is done using the woocommerce_my_account_my_address_formatted_address
filter and a call to get_user_meta()
. The filter receives a keyed array of all of the address data as the first argument and the current customer’s ID as the second.
Step 4 – Mapping the replacement to the template:
Now that we have {vat}
available in the template and a vat
data key in the address, it’s time to map the two together so they will be merged.
This is done using the woocommerce_formatted_address_replacements
filter which receives a keyed array of placeholders and their corresponding replacement as the first argument and the address data from step 3 as the second.
Notice how we matched the vat
key with step 3. We also account for customers who have not set a VAT by replacing {vat}
with an empty string.