【发布时间】:2020-06-22 10:51:04
【问题描述】:
我正在尝试将我的 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 个类别中订购产品。例如,一旦他们将“糖果”类别的产品添加到购物篮中,他们就无法添加“糖果”以外的任何其他类别的产品。
谢谢!
【问题讨论】:
标签: wordpress woocommerce cart