WooCommerce PHP Intermediate Requires WooCommerce

Add a Custom Field to Checkout

Ask customers an extra question at checkout, such as a gift message or how they heard about you, using WooCommerce's checkout fields API.

Tested on WordPress 7.1 PHP 8.3 Updated
functions.php 20 lines
add_action( 'woocommerce_init', function (): void {
	// The Additional Checkout Fields API works with the block-based Checkout.
	if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
		return;
	}

	woocommerce_register_additional_checkout_field( [
		'id'       => 'nahnu/how-did-you-hear',
		'label'    => 'How did you hear about us?',
		'location' => 'order',
		'type'     => 'select',
		'required' => false,
		'options'  => [
			[ 'value' => 'search', 'label' => 'Search engine' ],
			[ 'value' => 'social', 'label' => 'Social media' ],
			[ 'value' => 'friend', 'label' => 'A friend' ],
			[ 'value' => 'other', 'label' => 'Something else' ],
		],
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Sometimes you need one more piece of information with an order. WooCommerce has an official way to add fields to the block-based Checkout, which also saves the answer and shows it on the order.

How it works

On woocommerce_init, the snippet registers a field with woocommerce_register_additional_checkout_field(). The location decides where it appears: contact (with the email address), address (in both address forms) or order (in a section before the Place Order button).

WooCommerce validates and saves the answer for you, and shows it on the order screen in wp-admin and in order emails. Types include text, select and checkbox.

Things to watch

  • The field id needs a namespace, like nahnu/how-did-you-hear. Use your own prefix.
  • The API needs WooCommerce 8.9 or later, and it adds fields to the block-based Checkout. The classic shortcode checkout uses the woocommerce_checkout_fields filter instead.
  • Read a saved value in code with $order->get_meta( '_wc_other/nahnu/how-did-you-hear' ).

How to test it

Open the block-based Checkout. The question should appear above the Place Order button. Place an order, then open it in WooCommerce → Orders to see the answer.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only