'Validate if product added to cart has selected variable value Woocommerce
I'm wondering how to validate if user has filled the input with personalization field. So in this case i've added function:
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Setting
$attribute = 'pa_personalizacja';
// Real product ID
$product_id = $variation_id > 0 ? $variation_id : $product_id;
// Get product
$product = wc_get_product( $product_id );
// Get the product attribute value
$product_attribute = $product->get_attribute( $attribute );
// Initialize
$flag = false;
// WC Cart
if ( WC()->cart ) {
// Get cart
$cart = WC()->cart;
// If cart is NOT empty
if ( ! $cart->is_empty() ) {
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
// Get the product attribute value
$cart_item_attribute = $cart_item['data']->get_attribute( $attribute );
// NOT equal
if ( $cart_item_attribute == 'Personalizowany' empty( $_REQUEST['name-on-toys'] )) {
// Flag becomes true
$flag = true;
// Break loop
break;
}
}
}
}
// True
if ( $flag ) {
// Display an error message
wc_add_notice( __( 'Wpisz imię do personalizacji', 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
I would like to display an error if user choose variation value named "Personalizowany" and if the "name-on-toys" field is empty. Second condition works, but first not - the error appears even if "Personalization" variation is not selected. How can I make it work?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
