WooCommerce: Hide Checkout Fields For Virtual Products
I’ve been asked many times how to remove specific fields on the checkout page when the cart contains virtual (downloadable) products only. By default if the cart contains virtual products only, the shipping fields are automatically removed, but some users want to remove some of the billing fields too. That’s understandable, there’s no need to collect the billing address or the billing zipcode in most cases. The snippet i wrote below, checks the number of products in the cart, and compare the result to the number of virtual products in the cart. If all products are virtual, then checkout fields are removed, if the cart contains one virtual product and at least one physical product, checkout fields are kept. Does that make sense?
The code below has a function called woo_cart_has_virtual_product(). That’s the one checking for the virtual products in the cart. It returns true if all products in the cart are virtual, and false, if none of them are virtual or if there’s at least one non virtual product in the cart. Then the second function, woo_remove_billing_checkout_fields(), is hooked to woocommerce_checkout_fields and delete the unwanted checkout fields.
Here is the result when your cart contains virtual products only:
The code
<?php
add_filter( 'woocommerce_checkout_fields' , 'woo_remove_billing_checkout_fields' );
/**
* Remove unwanted checkout fields
*
* @return $fields array
*/
function woo_remove_billing_checkout_fields( $fields ) {
if( woo_cart_has_virtual_product() == true ) {
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;
}
/**
* Check if the cart contains virtual product
*
* @return bool
*/
function woo_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 )
$has_virtual_products = true;
return $has_virtual_products;
}