Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' );
like image 431
ScottyBoy Avatar asked Oct 16 '25 13:10

ScottyBoy


1 Answers

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.

like image 121
LoicTheAztec Avatar answered Oct 18 '25 08:10

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!