ScottyBoy
ScottyBoy

Reputation: 63

Show custom checkout fields if a specific product is in cart on Woocommerce

So I have some custom fields in my billing section on the checkout page, that I only want to display if a product with ID (603) is in the cart.

Currently, my code below works to hide the fields if there is a product in the cart that is not id 603, but one issue is when I have 603 and another product in the cart it unsets the fields,

what is the best way to either hide the fields if 603 is not in the cart or to just show them if it is?

this is the current code I was using

    function conditional_checkout_fields_products( $fields ) {
        $cart = WC()->cart->get_cart();

        foreach ( $cart as $item_key => $values ) {
            $product = $values['data'];

            if ( $product->id != 603 ) {
                unset( $fields['billing']['billing_prev_injuries'] );
                unset( $fields['billing']['billing_dogs_events'] );
                unset( $fields['billing']['billing_dogs_age'] );
                unset( $fields['billing']['billing_dogs_breed'] );
                unset( $fields['billing']['billing_dogs_name'] );
              }
        }

        return $fields;
    }
add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );

Upvotes: 4

Views: 3391

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254398

The following will do the job:

add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );
function conditional_checkout_fields_products( $fields ) {
    $is_in_cart = false;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( $cart_item['data']->get_id() == 603 ) {
            $is_in_cart = true;
            break;
        }
    }

    if ( ! $is_in_cart ) {
        unset( $fields['billing']['billing_prev_injuries'] );
        unset( $fields['billing']['billing_dogs_events'] );
        unset( $fields['billing']['billing_dogs_age'] );
        unset( $fields['billing']['billing_dogs_breed'] );
        unset( $fields['billing']['billing_dogs_name'] );
    }

    return $fields;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 5

Related Questions