PHP Snippet 1:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_supplier_by_order', 10, 2 );
function only_one_supplier_by_order( $passed, $product_id ) {
if ( WC()->cart->is_empty() )
return $passed;
$taxonomy = 'supplier';
$term_ids = wp_get_post_terms( $product_id, $taxonomy, ['fields' => 'ids']);
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
if( ! has_term( $term_ids, $taxonomy, $cart_item['product_id'] ) ) {
// Displaying a custom notice
wc_add_notice( __('This product is with a different supplier. Please only order from 1 supplier at a time.'), 'error' );
return false; // Avoid add to cart
}
}
return $passed;
}
PHP Snippet 2:
// To be sure (avoiding checkout)
add_action( 'woocommerce_check_cart_items', 'only_one_supplier_by_order_check' );
function only_one_supplier_by_order_check() {
$taxonomy = 'supplier';
$term_names = []; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
$terms = wp_get_post_terms( $cart_item['product_id'], $taxonomy );
if( ! empty($terms) ) {
$term = reset($terms);
$term_names[$term->term_id] = $term->name;
}
}
// Allow only one supplier in cart (avoid checkout for more than one
if( count( $term_names ) > 1 ) {
// Displaying a custom notice
wc_add_notice( __('Only items from one supplier at the time are allowed in cart'), 'error' );
}
}