I’m trying to restrict the user to only being able to add items to the cart from one grouped product at a time.
I’ve tried writing the code in two different approaches but neither work.
These are my 2 attempts.
Attempt One:
function limit_cart_items_to_one_group ( $passed, $product_id, $quantity ) {
if (current_user_can('stallholder') ) {
if( WC()->cart->is_empty() ) return $passed;
$product_type = array('terms' => array('grouped'));
$products = wc_get_products( $args );
$found = $current = false;
foreach ( $products as $product ) {
$children = array();
foreach ( $product->get_children() as $child_id ) {
$children[] = $child_id;
}
}
if( has_term( $children, 'product_cat', $product_id ) ){
$current = true;
}
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( $children, 'product_cat', $cart_item['product_id'] ) ) {
$found = true;
$current = true;
break; // stop the loop.
}
}
if( $found && $current ){
$passed = false;
$cats_str = implode('" and "', $children );
wc_add_notice( sprintf( __('Only one Market date is allowed to be booked at a time. Thank you.', 'woocommerce' ), $cats_str ), 'error' );
}
return $passed;
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_to_one_group', 10, 3 );
Attempt 2:
function is_product_the_same_group($valid, $product_id, $quantity) {
if (current_user_can('stallholder') ) {
$product_type = array('terms' => array('grouped'));
$products = wc_get_products( $args );
foreach ( $products as $product ) {
$children = array();
foreach ( $product->get_children() as $child_id ) {
$children[] = $child_id;
}
}
global $woocommerce;
if($woocommerce->cart->cart_contents_count == 0){
return true;
}
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, $children );
$target_terms = get_the_terms( $product_id, $children );
foreach ($terms as $term) {
$group_ids[] = $term->term_id;
}
foreach ($target_terms as $term) {
$target_group_ids[] = $term->term_id;
}
}
$same_group = array_intersect($group_ids, $target_group_ids);
if(count($same_group) > 0) return $valid;
else {
wc_add_notice( 'This product is in another group!', 'error' );
return false;
}
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_group',10,3);
Basically I’m trying to restrict what this specific user role to only being able to book from one group of products at a time.