Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Orders and Checkout

Classic Checkout Fields and Validation

Customize the classic WooCommerce checkout: edit fields with woocommerce_checkout_fields, validate input, save it to the order and show it in admin and emails.

The checkout form is where a visitor becomes a customer, so every field on it costs you conversions and every missing field costs you data. Shops constantly ask for the same changes: remove the company field, make the phone number required, add a VAT number or a delivery note, and check that the value makes sense before an order is created.

This lesson is about the classic (shortcode) checkout: the form rendered by templates and processed by PHP. You will learn how to change the field list with a filter, how validation runs, how to save extra data on the order, and how to show it in the admin screen and in emails, with sanitizing and escaping done correctly. The block-based checkout uses a different mechanism, covered in Cart and Checkout Blocks Extensibility. For the shop-owner view of a good checkout, see Checkout Flow. Real WooCommerce code is read-only here; the runnable examples are stand-ins in plain PHP.

Many stores now use the checkout block, and the filters in this lesson do not change it. Before you promise a client a custom field, check which checkout the store uses, and decide whether your plugin supports one or both.

The field list and its groups

All fields of the classic checkout live in one array, filtered by woocommerce_checkout_fields. The array has four groups: billing, shipping, account and order (the "Order notes" box). Each group maps a field key to its settings:

PHP
<?php
add_filter( 'woocommerce_checkout_fields', function ( array $fields ): array {
    // 1. Remove a field.
    unset( $fields['billing']['billing_company'] );

    // 2. Change an existing field.
    $fields['billing']['billing_phone']['required'] = true;
    $fields['billing']['billing_phone']['priority'] = 25;

    // 3. Add a field.
    $fields['billing']['billing_vat_number'] = array(
        'type'        => 'text',
        'label'       => __( 'VAT number', 'acme' ),
        'placeholder' => 'DE123456789',
        'required'    => false,
        'class'       => array( 'form-row-wide' ),
        'priority'    => 35,
    );

    return $fields;
} );

The most useful settings are:

Setting Meaning
type text, textarea, select, checkbox, email, tel, number, date, and others.
label, placeholder, description What the shopper sees. Wrap text in translation functions.
required Whether an empty value is rejected by the built-in check.
class, label_class, input_class CSS classes, for layout (form-row-first, form-row-wide).
priority Sort order inside the group; lower comes first.
options For select and radio: an array of value to label.
validate A list of built-in checks, such as email, phone, postcode or state.
autocomplete The HTML autocomplete token, for example tel.

Two notes. Keep keys prefixed with the group (billing_..., shipping_...), because that is how core finds and saves them. And avoid removing fields that other parts of WooCommerce depend on: the country, state and postcode fields drive tax and shipping calculations (Taxes, Currency and Formatting). Removing the email field breaks order emails. Make fields optional before you remove them.

How checkout validation runs

When the shopper presses "Place order", the checkout request goes through these stages:

flowchart TD
  A["Place order clicked"] --> B["Read and clean posted data"]
  B --> C["Built-in checks:<br/>required, email, phone, postcode"]
  C --> D["woocommerce_checkout_process<br/>(action)"]
  D --> E["woocommerce_after_checkout_validation<br/>(data, errors)"]
  E -->|"any errors"| F["Show errors, no order created"]
  E -->|"no errors"| G["Create order"]
  G --> H["woocommerce_checkout_create_order<br/>save custom data"]

Validation happens before an order exists; saving custom data happens while the order object is being built.

You have two places to add rules:

  1. woocommerce_checkout_process is an action with no arguments. You read $_POST yourself and report problems with wc_add_notice( $message, 'error' ). It is the older style, and it means you must sanitize raw input manually.
  2. woocommerce_after_checkout_validation is a filter-like action with two arguments: the cleaned $data array and a WP_Error object. You call $errors->add( 'code', 'Message' ). It runs after the built-in checks, so your rule can rely on the cleaned values. For new code this is the better choice.
PHP
<?php
add_action( 'woocommerce_after_checkout_validation', function ( array $data, WP_Error $errors ): void {
    $vat = strtoupper( preg_replace( '/\s+/', '', (string) ( $data['billing_vat_number'] ?? '' ) ) );

    if ( '' !== $data['billing_company'] && '' === $vat ) {
        $errors->add( 'acme_vat_missing', __( 'Please enter a VAT number for company orders.', 'acme' ) );
        return;
    }

    if ( '' !== $vat && ! preg_match( '/^[A-Z]{2}[A-Z0-9]{2,12}$/', $vat ) ) {
        $errors->add( 'acme_vat_format', __( 'The VAT number does not look valid.', 'acme' ) );
    }
}, 10, 2 );

Good validation messages say what is wrong and how to fix it, and they are translatable. Do not reveal internals. Remember that this check is only a format check: confirming that a VAT number really exists means calling an external service, which should be time-limited and should never block checkout if the service is down (see the security and gateway lessons for the same caution with remote calls).

Client-side hints (an HTML pattern attribute, or JavaScript) are a convenience for the shopper, never a protection. A request can always skip them, so the PHP check is the one that counts (Sanitizing and Validating).

Saving the data on the order

Fields in the billing and shipping groups with a custom key such as billing_vat_number are stored on the order as meta for you, with a leading underscore (_billing_vat_number). Fields in the order group, or values you compute, you must save yourself in woocommerce_checkout_create_order, which runs before the order is saved, so you only set meta on the object:

PHP
<?php
add_action( 'woocommerce_checkout_create_order', function ( WC_Order $order, array $data ): void {
    $slot = isset( $_POST['acme_delivery_slot'] )
        ? sanitize_text_field( wp_unslash( $_POST['acme_delivery_slot'] ) )
        : '';

    if ( in_array( $slot, array( 'morning', 'afternoon' ), true ) ) {
        $order->update_meta_data( '_acme_delivery_slot', $slot );
    }
}, 10, 2 );

Three rules:

  • Sanitize on input: wp_unslash() first (WordPress adds slashes to superglobals), then sanitize_text_field() or wc_clean() for plain text. Allow-list values for choices, like the in_array() check above. A nonce is already checked by the checkout itself for its own fields; do not add a second form.
  • Use the order's CRUD methods, not update_post_meta(), so that your plugin works with HPOS (Orders and High-Performance Order Storage).
  • Prefix keys with your plugin's name and start them with an underscore so they stay out of the generic "custom fields" list. Underscore-prefixed meta is hidden from that list but is not secret; do not store secrets on orders.

The older hook woocommerce_checkout_update_order_meta receives only an order ID and is still seen in older plugins. New code should prefer woocommerce_checkout_create_order.

Showing the data in the admin and in emails

Saved data is useless if nobody sees it. For the order edit screen, print the value after the billing address and escape on output:

PHP
<?php
add_action( 'woocommerce_admin_order_data_after_billing_address', function ( WC_Order $order ): void {
    $vat = $order->get_meta( '_billing_vat_number' );
    if ( $vat ) {
        printf( '<p><strong>%s:</strong> %s</p>', esc_html__( 'VAT number', 'acme' ), esc_html( $vat ) );
    }
} );

For emails, the filter woocommerce_email_order_meta_fields lets you add labeled lines. It receives the current fields, whether the email goes to the admin, and the order:

PHP
<?php
add_filter( 'woocommerce_email_order_meta_fields', function ( array $fields, bool $sent_to_admin, WC_Order $order ): array {
    $vat = $order->get_meta( '_billing_vat_number' );
    if ( $vat ) {
        $fields['acme_vat'] = array(
            'label' => __( 'VAT number', 'acme' ),
            'value' => $vat,
        );
    }
    return $fields;
}, 10, 3 );

For the customer's order-received page and "My account" order view, use the woocommerce_order_details_after_customer_details action. Sanitizing on input does not replace escaping on output: input rules can change, old orders may contain other data, and a different plugin may write the same meta. See Escaping Output.

A runnable checkout validator

This stand-in mirrors the structure: a field list that a filter edits (removing, requiring, adding), then a validator that applies required checks, built-in validators and a custom rule that receives cleaned data and an error collection. It is not WooCommerce; it shows the order of operations.

PHP Editing the field list and validating a checkout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What is real: the field groups, the required and validate settings, the order of checks, and the idea of passing cleaned data and an error collection to your rule. The pattern checks are simplified.

Saving and displaying safely

The second stand-in covers the path after validation: custom billing_ keys land in meta with an underscore, an order-group value is saved by your own hook after allow-listing, and the admin and email output is escaped. The hostile text in the delivery note shows why output escaping matters.

PHP Saving to order meta and rendering escaped output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The meta key _acme_delivery_slot is absent on purpose: evening is not in the allow-list, so nothing is saved. In real code you would also add an error during validation so the shopper knows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which filter lets you add, remove and edit fields of the classic checkout form?

    woocommerce_checkout_fields receives the whole field array grouped as billing, shipping, account and order. The other hooks relate to the cart or to single field output.
  2. 2. What is the best way to reject an invalid value, with the cleaned checkout data available?

    That hook runs after the built-in checks and receives the cleaned data and a WP_Error. Adding an error stops order creation and shows the message. HTML attributes can be bypassed.
  3. 3. Where do you set custom meta on the order while it is being created from the checkout?

    The hook receives the order object before it is saved, so you set meta with CRUD methods and the order is saved once. This also works with HPOS.
  4. 4. A customer note is sanitized when saved. Why should you still escape it when printing it in the admin?

    Input sanitizing and output escaping solve different problems. Escape late with esc_html() or a similar function every time you print.
  5. 5. Why is it risky to remove the billing country field?

    Rates for tax and shipping are chosen by country, state and postcode. Make such fields optional or preset a default instead of removing them.

Summary

  • The classic checkout fields are one array in woocommerce_checkout_fields, in the groups billing, shipping, account and order; edit it with unset, changed settings and new entries with a priority.
  • Keep keys prefixed with their group, and do not remove fields that tax, shipping or emails need.
  • Validate in woocommerce_after_checkout_validation by adding errors to the WP_Error; client-side checks are only hints.
  • Save custom values in woocommerce_checkout_create_order with update_meta_data(), sanitize and allow-list them, and prefix keys with an underscore and your plugin name.
  • Show data in admin and emails with woocommerce_admin_order_data_after_billing_address and woocommerce_email_order_meta_fields, escaping on output.
  • These filters apply to the classic checkout only; the block checkout needs its own approach.

Next: Cart and Checkout Blocks Extensibility