我试图限制 Woocommerce 商店的客户一次只能从 1 个“供应商”订购产品。我通过称为“供应商”的自定义分类来定义“供应商”。我正在尝试的代码只是出于某种原因限制了一切。
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// If passed
if ( $passed ) {
// If cart is NOT empty when a product is added
if ( !WC()->cart->is_empty() ) {
// Set vars
$current_product_tag_ids = array();
$in_cart_product_tag_ids = array();
// Get current product categories via product_id
$current_product_tag_ids = wc_get_product_term_ids( $product_id, 'supplier' );
// Loop through cart items checking for product categories
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Get product categories from product in cart via cart item product id
$in_cart_product_tag_ids = array_merge( $in_cart_product_tag_ids, wc_get_product_term_ids( $cart_item['product_id'], 'product_cat' ) );
}
// Removes duplicate values
$in_cart_product_tag_ids = array_unique( $in_cart_product_tag_ids, SORT_NUMERIC );
// Compare
$compare = array_diff( $current_product_tag_ids, $in_cart_product_tag_ids );
// Result is NOT empty
if ( !empty ( $compare ) ) {
wc_add_notice( 'This product is with a different supplier. Please only order from 1 supplier at a time.', 'error' );
$passed = false;
}
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
我并不是试图将其限制为每个供应商 1 个产品,而是试图限制他们,以便他们每个订单只能从 1 个供应商处订购产品。例如,一旦他们将供应商“供应商 1”的产品添加到购物篮中,他们将无法添加“供应商 1”以外的任何其他供应商的产品。
守着一只汪