GeneratorsWooCommerceCheckout Fields

Checkout Fields Generator

Extra checkout fields for whichever checkout renderer this site uses — the classic woocommerce_checkout_fields filter, or the Blocks Checkout's own field-registration API.

acme-checkout-fields.php
Saved just now
Fields
1 field
VAT numbervat_id
Required
Naming
Classic checkout keys are prefixed by location automatically — billing_vat_id, shipping_vat_id, and so on.
The woocommerce_checkout_fields filter — for the [woocommerce_checkout] shortcode.
<?php
// Generated with WP CodeKit — powered by GrowQuest (https://growquest.io).
/**
 * Plugin Name:       Checkout fields
 * Description:       Adds 1 field to classic checkout.
 * Version:           1.0.0
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 */

defined( 'ABSPATH' ) || exit;

/**
 * Add fields to the classic checkout form.
 *
 * @param array $fields Existing fields, grouped by section.
 * @return array
 */
function acme_checkout_fields( $fields ) {
	$fields['billing']['billing_vat_id'] = array(
		'label'       => __( 'VAT number', 'acme' ),
		'required'    => false,
		'class'       => array( 'form-row-wide' ),
		'placeholder' => __( 'e.g. GB123456789', 'acme' ),
	);

	return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'acme_checkout_fields' );

/**
 * Save the values onto the order — before it is written, so this
 * runs whether the order ends up in wp_posts or the HPOS tables.
 *
 * @param WC_Order $order The order being created.
 * @param array    $data  The posted checkout data.
 */
function acme_save_checkout_fields( $order, $data ) {
	if ( ! empty( $_POST['billing_vat_id'] ) ) {
		$order->update_meta_data( '_billing_vat_id', sanitize_text_field( wp_unslash( $_POST['billing_vat_id'] ) ) );
	}
}
add_action( 'woocommerce_checkout_create_order', 'acme_save_checkout_fields', 10, 2 );

/**
 * Show the billing fields on the order edit screen.
 *
 * @param WC_Order $order The order.
 */
function acme_display_billing_meta( $order ) {
	$value = $order->get_meta( '_billing_vat_id' );

	if ( $value ) {
		echo '<p><strong>' . esc_html( __( 'VAT number', 'acme' ) ) . ':</strong> ' . esc_html( $value ) . '</p>';
	}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'acme_display_billing_meta' );