· wphelp.blog · wp-cli 2.x · php 8.5 · wp 7.2 · online [ ✓ tests passing ]

WooCommerce: How to hide fields at checkout for virtual products

culprit

·

·

# , ,

·

2 min

Answer me this question: is it necessary to ask for street, postal code, city and country for virtual products in an online store?

If the answer is no, why does WooCommerce by default show all those fields and more even when the cart only has a virtual product, which doesn’t need to be sent anywhere?

Aren’t we complicating the sale this way, asking for things that any average alert customer will realize is unnecessary? Doesn’t this transmit a bad impression of our Ecommerce, by asking for more than necessary?

I’m referring to things like asking for all those not virtual data when you’re buying a virtual product…

What’s more how does this overdose of information requests fit with the principles of privacy protection laws like GDPR?

If you’re with me in thinking it’s excessive, open right now the file functions.php or your plugin to customize things and add this code:

/**
* Check if the current cart contains only virtual products.
*
* Returns false if WooCommerce is not active or the cart is not
* initialized (admin, customizer, REST, WP-CLI, cron...).
 */
function wphelp_virtual_checkout_only() {

if ( ! function_exists( 'WC' ) ) {
return false;
}

$carrito = WC()->cart;

if ( ! $cart instanceof WC_Cart || $cart->is_empty() ) {
return false;
}

foreach ( $cart->get_cart() as $item ) {

if ( empty( $item['data'] ) || ! $item['data'] instanceof WC_Product ) {
continue;
}

if ( ! $item['data']->is_virtual() ) {
return false;
}
}

return true;
}

/* Remove unnecessary fields if the cart is only virtual */
add_filter( 'woocommerce_checkout_fields', 'wphelp_virtual_checkout' );
function wphelp_virtual_checkout( $fields ) {

if ( ! wphelp_virtual_checkout_only() ) {
return $fields;
}

$remove = array(
'billing_company',
'billing_address_1',
'billing_address_2',
'billing_city',
'billing_postcode',
'billing_state',
'billing_phone',
);

foreach ( $remove as $field ) {
unset( $fields['billing'][ $field ] );
}

return $fields;
}

/* Hide order notes if the cart is only virtual */
add_filter( 'woocommerce_enable_order_notes_field', 'wphelp_virtual_checkout_notes' );
function wphelp_virtual_checkout_notes( $activated ) {
return wphelp_virtual_checkout_only() ? false : $activated;
}

Save your changes to see how lightweight, reasonable, respectful of privacy, effective your checkout page looks

Do you want to keep asking for the phone for some reason?, well you delete the line that removes unset from billing_phone, and you can personalize it to your liking.

Less asking and more selling! 😀

Share on social media
Summarize with AI
┌─ @culprit ─┐

# your opinion matters · or not · depends

# seriously, still thinking about it?