This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

How to remove billing address fields from WooCommerce checkout form if there are only virtual products in the cart [WooCommerce Code Snippet]

WooCommerce allows you to sell physical as well as digital / virtual / downloadable products. In case of physical products, we need to collect billing and shipping address because goods need to be delivered to the customers. However in case of digital products, we don’t need to deliver goods and so it does not make sense to collect billing address.

This is actually one of the features my client wanted who has an online store where she sells hard cover books as well as digital copies. For smooth checkout process she requested a feature where users ordering digital copies only should not go through the hassle of filling billing address details.

Here’s the code snippet for the same:

add_filter('woocommerce_checkout_fields','wooc_custom_checkout_fields');

function wooc_custom_checkout_fields( $fields ) {
	if( wooc_cart_has_virtual_product() == true ) { //helper function to check if there are only virtual products in the cart
		unset($fields['billing']['billing_first_name']);
		unset($fields['billing']['billing_last_name']);
		unset($fields['billing']['billing_company']);
		unset($fields['billing']['billing_address_1']);
		unset($fields['billing']['billing_address_2']);
		unset($fields['billing']['billing_city']);
		unset($fields['billing']['billing_postcode']);
		unset($fields['billing']['billing_country']);
		unset($fields['billing']['billing_state']);
		unset($fields['billing']['billing_phone']);
	}
	return $fields;
}


function wooc_cart_has_virtual_product() {
	global $woocommerce;
	
	// By default, no virtual product
	$has_virtual_products = false;
	
	// Default virtual products number
	$virtual_products = 0;
	
	// Get all products in cart
	$products = $woocommerce->cart->get_cart();
	
	// Loop through cart products
	foreach( $products as $product ) {
		// Get product ID and '_virtual' post meta
		$product_id = $product['product_id'];
		$is_virtual = get_post_meta( $product_id, '_virtual', true );
		// Update $has_virtual_product if product is virtual
		if( $is_virtual == 'yes' ) {
			$virtual_products += 1;
		}
	}
	if( count($products) == $virtual_products ) { //match the count with the products in the cart
		$has_virtual_products = true;
		}
	return $has_virtual_products;
}