[英]WooCommerce: Only allow products from the same category in cart
I'm wanting to stop customers from being able to add items from other categories once an item has been added to the cart.我想阻止客户在将商品添加到购物车后添加其他类别的商品。 The customer should still be able to add items from the same category.
客户应该仍然能够添加来自同一类别的项目。
Here is what I have so far:这是我到目前为止所拥有的:
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);
This works if I already have an item in my cart but it doesn't let me add anything from an empty cart and always displays the error message.如果我的购物车中已经有一件商品,这会起作用,但它不允许我从空购物车中添加任何东西,并且总是显示错误消息。
Thanks!谢谢!
After some tweaking I think I figured it out: 经过一些调整后,我想我知道了:
# #
function is_product_the_same_cat($valid, $product_id, $quantity) {
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, 'product_cat' );
$target_terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
$cat_ids[] = $term->term_id;
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $term->term_id;
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids);
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);
In your is_product_the_same_cat
method, your have not added any code to perform when the cart is empty. 在您的
is_product_the_same_cat
方法中,您没有添加任何在购物车为空时执行的代码。 May be because of that you cant add when cart is empty. 可能是因为购物车为空时您无法添加。
Add following code after global $woocommerce; 在全局$ woocommerce之后添加以下代码; line
线
if ( woocommerce()->cart->get_cart_contents_count() == 0 ) {
return true;
}
This works for my products that are "simple product", but not for my products that are "product bundle".这适用于我的“简单产品”产品,但不适用于我的“产品捆绑”产品。 They don't have a different category so I am not sure why.
他们没有不同的类别,所以我不知道为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.