WooCommerce: Customize Checkout Fields Based on Product Type

In WooCommerce, you may encounter scenarios where you want to customize the checkout fields based on the type of products in the cart. For example, if the customer has virtual or downloadable products in their cart, you might want to streamline the checkout process by removing unnecessary address fields and adding required fields like email.

/**
* Snippet Name:  Customize Checkout Fields Dynamically
* Snippet Author:  wpsnippets.dev
*/

//Customize Checkout Fields Based on Product Type
function wps_custom_checkout_fields_based_on_product_type( $fields ) {
    // Check if there are virtual or downloadable products in the cart
    $has_virtual_or_downloadable = false;
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        if ( $product->is_virtual() || $product->is_downloadable() ) {
            $has_virtual_or_downloadable = true;
            break;
        }
    }
  // Remove unnecessary fields if virtual or downloadable products are present
    if ( $has_virtual_or_downloadable ) {
        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['shipping']['shipping_address_1'] );
        unset( $fields['shipping']['shipping_address_2'] );
        unset( $fields['shipping']['shipping_city'] );
        unset( $fields['shipping']['shipping_postcode'] );
        unset( $fields['shipping']['shipping_country'] );
        unset( $fields['shipping']['shipping_state'] );

        $fields['billing']['billing_email']['required'] = true;   // Add required email field
    }

    return $fields;
}
add_action( 'woocommerce_checkout_fields', 'wps_custom_checkout_fields_based_on_product_type' ); //removing fields

Code Explanation

  • This code dynamically alters WooCommerce checkout fields based on the presence of virtual or downloadable products in the cart. It hooks into the “woocommerce_checkout_fields” hook and executes the function “wps_custom_checkout_fields_based_on_product_type()” to make these adjustments.
  • Specifically, it removes unnecessary address fields and sets the email field as required if virtual or downloadable products are detected in the cart.

Leave a Comment

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

Scroll to Top