Reputation: 35
I need to make order notes required only on certain product categories (eg if someone buys "cards", they have to fill in a message).
I've found this snippet to make order notes required, I just need to set it to be associated with a certain product.
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['order']['order_comments']['required'] = true;
return $fields;
}
Upvotes: 1
Views: 857
Reputation: 253783
The following will make checkout order notes field required for specific product(s) category(ies):
// Conditional function that check for specific product(s) category(ies)
function is_product_category_terms_in_cart( $categories ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
return true;
}
}
return false;
}
// Make order notes required field conditionally
add_filter( 'woocommerce_checkout_fields' , 'make_order_notes_required_field' );
function make_order_notes_required_field( $fields ) {
// Set in the array your targeted product category term(s)
$categories = array("cards");
if ( is_product_category_terms_in_cart( $categories ) ) {
$fields['order']['order_comments']['required'] = true;
}
return $fields;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Upvotes: 2