我正在尝试限制 WooCommerce 商店中的客户一次只能订购 1 个类别。
我正在尝试的代码只是出于某种原因限制一切。
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
$target_terms = get_the_terms( $product_id, 'product_cat' ); //get the current items
foreach ($terms as $term) {
$cat_ids[] = $term->term_id; //get all the item categories in the cart
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $term->term_id; //get all the categories of the product
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids); //check if they have the same category
if(count($same_cat) > 0) return $valid;
else {
wc_add_notice( 'This product is in another category!', 'error' );
return false;
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);
我并不是试图将其限制为每个类别 1 个产品,而是试图限制他们,以便他们每个订单只能订购 1 个类别的产品。
一旦他们将“糖果”类别中的产品添加到购物篮中,他们将无法添加“糖果”以外的任何其他类别的产品。
假设每个产品只包含1个类别
wc_get_product_term_ids
,这意味着不需要循环来获取术语ID。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_category_ids = array();
$in_cart_product_category_ids = array();
// Get current product categories via product_id
$current_product_category_ids = wc_get_product_term_ids( $product_id, 'product_cat' );
// 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_category_ids = array_merge( $in_cart_product_category_ids, wc_get_product_term_ids( $cart_item['product_id'], 'product_cat' ) );
}
// Removes duplicate values
$in_cart_product_category_ids = array_unique( $in_cart_product_category_ids, SORT_NUMERIC );
// Compare
$compare = array_diff( $current_product_category_ids, $in_cart_product_category_ids );
// Result is NOT empty
if ( !empty ( $compare ) ) {
wc_add_notice( 'This product is in another category!', 'error' );
$passed = false;
}
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );