Checkout

WooCommerce Add Custom Checkout Field If Specific Product Is In Cart

WooCommerce checkout showing custom conditional field

Pre-Requisites

There are no pre-requisites in order for you to be able to implement this solution.

How To Implement This Solution?

Simply copy the pre-coded solution to your active theme’s functions.php or preferably the Code Snippets Plugin.

About This Solution

This snippet will show a custom checkout field and save the data as order meta ONLY IF a specific product is in the cart.

/**
 * Snippet Name:	WooCommerce Add Custom Checkout Field If Specific Product Is In Cart
 * Snippet Author:	ecommercehints.com
 */

// Create the custom checkout text field in the billing section of the checkout form
add_action( 'woocommerce_after_checkout_billing_form', 'ecommercehints_conditional_checkout_field' );
function ecommercehints_conditional_checkout_field($checkout) {
	if(WC()->cart->find_product_in_cart(WC()->cart->generate_cart_id(282))) {	// The Product ID to trigger the new custom field
		woocommerce_form_field( 'team_name', array(
			'type'          => 'text',
			'class'         => array('form-row-wide'),
			'required'		=> 'true',
			'label'         => 'Pub Quiz Team Name',
		), $checkout->get_value('team_name') );
	}
}

// Show an error message of field is not populated
add_action('woocommerce_checkout_process', 'ecommercehints_custom_checkout_field_validation');
function ecommercehints_custom_checkout_field_validation() {
	if(WC()->cart->find_product_in_cart(WC()->cart->generate_cart_id(282))) {	// The Product ID to trigger the new custom field
		if (empty( $_POST['team_name'] ) ) {
			wc_add_notice( 'Please enter a team name for the pub quiz.', 'error' );
		}
	}
}

// Save the custom field data as order meta
add_action( 'woocommerce_checkout_update_order_meta', 'ecommercehints_save_custom_checkout_field' );
function ecommercehints_save_custom_checkout_field( $order_id ){
	if( !empty( $_POST['team_name'] ) ) {
		update_post_meta( $order_id, 'team_name', sanitize_text_field( $_POST['team_name'] ) );
	}
}

How The Checkout Field Is Saved

WooCommerce order dashboard showing custom checkout field data as order meta

Snippet Benefits

  • Capture additional data on the checkout if a specific product is in the cart.

100 WooCommerce Conversion Rate Optimisation Tips

This field is for validation purposes and should be left unchanged.

Let’s collaborate!

Need to outsource WordPress development?

Join forces with UnlimitedWP for an outsourced white label web development service you can truly rely on.

First Timer Here?

Sign up to receive 20% off on your first month with us.

26027
WELCOME OFFER