In WooCommerce checkout form I have customized the fields. However I don't want display these fields if a product belongs to a specific category. I have that part working.
Next I would like to unset some custom checkout fields, but I can't figure out how or now. Unsetting a normal checkout field is easy and I use for example the following code:
unset( $fields['billing']['billing_company'] );
However for a custom checkout field It doesn't work. Here is how I have set this custom field:
function company_details_section($checkout)
{
woocommerce_form_field('delegate_1_name', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide delegateExists'
) ,
'label' => __('Full name') ,
) , $checkout->get_value('delegate_1_name'));
}
As this belongs to its own section, and not the billing, shipping or normal WooCommerce additional fields, I can't find the way to remove it.
I have tried the following:
unset( $fields['delegate_1_name'] );
unset( $fields['additional']['delegate_1_name'] );
unset( $fields['billing']['delegate_1_name'] );
unset( $fields['shipping']['delegate_1_name'] );
unset( $fields['company_details_section']['delegate_1_name'] );
This is the conditional function that I am using to unset fields:
function wc_ninja_product_is_in_the_cart() {
// Add your special product IDs here
$ids = array( '45', '70', '75' );;
// Products currently in the cart
$cart_ids = array();
// Find each product in the cart and add it to the $cart_ids array
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$cart_product = $values['data'];
$cart_ids[] = $cart_product->id;
}
// If one of the special products are in the cart, return true.
if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
return true;
} else {
return false;
}
}
This is the functional code to unset normal checkout fields:
function wc_ninja_remove_checkout_field( $fields ) {
if ( ! wc_ninja_product_is_in_the_cart() ) {
unset( $fields['billing']['billing_company'] );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' );
How to unset custom checkout fields in WooCommerce (not classic ones)?