I have few variable products with variation that have pa_size
and pa_color
attributes (taxonomy). I have 4 sizes (“s”, “m”, “l” and “special”) and 4 colors.
My problem is, for the “special” size: Customer must fill order notes in checkout page, but since it is not a required field, they easily miss it.
I found some code for product categories that I have changed to handle pa_size
taxonomy. With this code I was thinking to make order notes checkout field required for purchased product variations with pa_size
attribute.
Here is my code:
function conditional_variation( $variations ) { foreach( WC()->cart->get_cart() as $cart_item ) { if( has_term( $variations, 'pa_size', $cart_item['product_id'] ) ) { return true; } } return false; } add_filter( 'woocommerce_checkout_fields' , 'make_order_notes_required_field' ); function make_order_notes_required_field( $fields ) { $variations = array("pa_size"); if ( conditional_variation( $variations ) ) { $fields['order']['order_comments']['required'] = true; } return $fields; }
But I can’t make it work.
I Tried many ways but I cant find a way to make it required for only “special” size attribute term. What I mean is if any variation combination or single product in cart contains “special” attribute (black-special, blue-special only “special” etc.) field must be required, otherwise (small-blue , red-large only red etc.) it must be optional.
Advertisement
Answer
Try the following instead (Be sure that “Special” is the right term name for pa_size
taxonomy set on the related variations of your variable product(s)):
add_filter( 'woocommerce_checkout_fields' , 'make_order_notes_required_field' ); function make_order_notes_required_field( $fields ) { $taxonomy = 'pa_size'; $term_name = 'Special'; foreach( WC()->cart->get_cart() as $cart_item ) { if( $cart_item['data']->get_attribute($taxonomy) === $term_name ) { $fields['order']['order_comments']['required'] = true; break; // Stop the loop } } return $fields; }
Code goes in functions.php file of the active child theme (or active theme). Tested and works.