WooCommerce:只允许购物车中相同类别的产品 [英] WooCommerce: Only allow products from the same category in cart

查看:74
本文介绍了WooCommerce:只允许购物车中相同类别的产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止客户将商品添加到购物车后再添加其他类别的商品.客户应该仍然可以添加同一类别的商品.

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.

谢谢!

推荐答案

经过一些调整后,我想我已经知道了:

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);

这篇关于WooCommerce:只允许购物车中相同类别的产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆