【发布时间】:2017-03-01 04:17:24
【问题描述】:
我想阻止客户在将商品添加到购物车后添加其他类别的商品。客户应该仍然可以添加同一类别的商品。
这是我目前所拥有的:
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);
如果我的购物车中已经有一件商品,但它不允许我从空购物车中添加任何东西并始终显示错误消息,则此方法有效。
谢谢!
【问题讨论】: