Remove all WooCommerce billing fields for virtual products

The following code checks to see if there are virtual products in the cart — if so, it will remove the billing fields from the WooCommerce checkout page as it is no longer needed. If there is at least one single physical item in the cart, though (mixed cart), then it keeps all the billing fields. If the cart is only physical products, no billing fields are removed.

add_filter( 'woocommerce_checkout_fields' , 'woo_remove_billing_checkout_fields' );

function woo_remove_billing_checkout_fields( $fields ) { 

if( wc_cart_has_virtual_products() == true ) {

  unset( $fields['billing']['billing_first_name'] );
  unset( $fields['billing']['billing_last_name'] );
  unset( $fields['billing']['billing_email'] );
  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']);
  unset( $fields['order']['order_comments']);
  unset( $fields['billing']['billing_address_2']);
  unset( $fields['billing']['billing_postcode']);
  unset( $fields['billing']['billing_company']);
  unset( $fields['billing']['billing_city']);
  }

return $fields; 

}

function wc_cart_has_virtual_products() { 

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
    if ($product['variation_id'] ) {
		  $product_id = $product['variation_id'];
	  } else {
		  $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 )
    $has_virtual_products = true;
  
  return $has_virtual_products;
}


Was this helpful? Please buy me a coffee






This code should be added to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin. Please don’t add custom code directly to your parent theme’s functions.php file as this will be wiped entirely when you update.

Share your thoughts

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