With WooCommerce, I would like to make checkout field billing_company required if a certain shipping class is applicable for the order.
I found similar code snippets, but they are all looking at the shipping method, not the class. I tried both options for $shipping_classes
in the next code snippet, but it's not working.
Any thoughts?
add_filter('woocommerce_checkout_fields', 'make_company_checkout_field_required');
function make_company_checkout_field_required($fields) {
$shipping_class ='heavy-shipping-class'; // Set the desired shipping class.
global $woocommerce;
//$shipping_classes = WC()->session->get( 'product_shipping_class' );
$shipping_classes = get_terms( array('taxonomy' => 'product_shipping_class' ) );
$chosen_shipping_class = $shipping_classes[0];
if ($chosen_shipping_class == $shipping_class) {
$fields['billing']['billing_company'][ 'required' ] = true;
}
return $fields;
}
add_filter('woocommerce_checkout_fields', 'make_company_checkout_field_required');
function make_company_checkout_field_required($fields) {
// Define the shipping class slug you want to check for
$shipping_class_slug = 'heavy-shipping-class'; // Adjust this to your desired shipping class slug
$make_company_required = false;
// Loop through all the items in the cart to check their shipping class
foreach (WC()->cart->get_cart() as $cart_item) {
// Get the product's shipping class ID
$product_shipping_class_id = $cart_item['data']->get_shipping_class_id();
// Get the shipping class object by ID
$shipping_class = get_term($product_shipping_class_id, 'product_shipping_class');
// Check if the product's shipping class matches the target class
if ($shipping_class && $shipping_class->slug === $shipping_class_slug) {
$make_company_required = true;
break; // No need to continue looping once we find a matching class
}
}
// If a product with the specified shipping class is found, make the company field required
if ($make_company_required) {
$fields['billing']['billing_company']['required'] = true;
}
return $fields;
}
Try to use this code for it.