1

我发现此代码将用户的购买限制为您选择的类别的每个类别一个。因此,目前用户可以从 cat a 购买 1 件商品。问题是,如果客户改变主意并添加与 cat a 不同的项目,我希望删除该项目。

$max_num_products ), 'error' ); 防止添加新产品和删除旧产品。(不需要 wc_add_notice)因为客户选择“送货”或“取货”

我添加了 WC()->cart->empty_cart(); // 这会清空整个购物车并添加新的选择...不是我需要的。

非常感谢任何帮助。

add_filter( 'woocommerce_add_to_cart_validation', 'allowed_quantity_per_category_in_the_cart', 10, 2 );function allowed_quantity_per_category_in_the_cart( $passed, $product_id) {

$max_num_products = 1;// change the maximum allowed in the cart
$running_qty = 0;

$restricted_product_cats = array();

//Restrict particular category/categories by category slug
$restricted_product_cats[] = 'cat-a';


// Getting the current product category slugs in an array
$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach($product_cats_object as $obj_prod_cat) $current_product_cats[]=$obj_prod_cat->slug;


// Iterating through each cart item
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){

    // Restrict $max_num_products from each category
    if( has_term( $current_product_cats, 'product_cat', $cart_item['product_id'] )) {

        // count(selected category) quantity
        $running_qty += (int) $cart_item['quantity'];

        // More than allowed products in the cart is not allowed
        if( $running_qty >= $max_num_products ) {
            wc_add_notice( sprintf( 'Only %s '.($max_num_products>1?'products from this category are':'product from this category is').' allowed in the cart.',  $max_num_products ), 'error' );

        //$passed = WC()->cart->empty_cart(); // this empties the entire cart and adds new selection... not what I need
          $passed = false; // don't add the new product to the cart
            // We stop the loop
            break;
        }

    }
}
return $passed;}
4

0 回答 0