首页 > 解决方案 > 在购物车 WooCommerce 中仅允许 1 种特定产品的数量

问题描述

我有一个可变产品 X,该产品有两个变体,变体 A 和变体 B。

如果客户在购物车中添加了变体 A,那么我想阻止客户在购物车中添加变体 B。一次客户只订购该产品的一种变体。

我已经添加了下面的代码,但它运行不佳,因为如果我在购物车中添加了产品 X 的一个变体,那么我尝试在购物车中添加另一个产品 Y,它不会添加到购物车中。

我的代码当前代码如下。

function wph_add_the_cart_validation_for_zoomarine_e_ticket( $passed ) { 
    // The product id of variable product X     
    $product_id = 44050;
    $in_cart = false;

    foreach( WC()->cart->get_cart() as $cart_item ) {
        $product_in_cart = $cart_item['product_id'];
       if ( $product_in_cart === $product_id ) $in_cart = true;
    }

   if ( $in_cart )  { ?>
       <script type="text/javascript">
           alert("The product is already in cart. You can only add one E ticket per order");
        </script>
   <?php
       $passed = false;
   }
   return $passed;
}

add_filter( 'woocommerce_add_to_cart_validation', 'wph_add_the_cart_validation_for_zoomarine_e_ticket', 10, 5 );

标签: phpwordpresswoocommercecart

解决方案


以下代码解决了我的问题。我从这里得到了答案https://wordpress.stackexchange.com/questions/349916/allow-only-1-quantity-of-particular-product-in-cart-woocommerce/349929#349929

add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );

function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {

    $product_a = 14576;
    $product_b = 14091;

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $cart_product_id = $cart_item['product_id'];
        if ($cart_item['variation_id']) {
            $cart_product_id = $cart_item['variation_id'];
        }

        if ( ($cart_product_id == $product_a && $variation_id == $product_b) || ($cart_product_id == $product_b && $variation_id == $product_a) ) {

            wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
            $passed = false; // don't add the new product to the cart
            // We stop the loop
            break;
        }
    }

    return $passed;
}

推荐阅读