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.
WooCommerce Conversion Rate Optimisation (CRO) eBook
100 WooCommerce Conversion Rate Optimisation Tips

Leave a Reply

If you are going to write code in the comments, please wrap it between code tags.

Your email address will not be published. Required fields are marked *

Other Recent Guides

Subscribe To Emails

Get exclusive WooCommerce tips that I only share with email subscribers

Join hundreds of other subscribers