不允许购物车中有特定数量的产品

时间:2020-09-21 10:04:01

标签: php woocommerce conditional-statements cart checkout

我们希望客户仅购买以下数量的产品。

  • 1袋
  • 2袋
  • 3袋
  • 4袋
  • 5袋
  • 10袋

到目前为止,我们已经成功地限制了可以在单个产品页面上选择的数量,

我们当前正在使用以下代码将用户限制为总共10个行李。

// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 10, 3 );

function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if( $cart_items_count >= 10 || $total_count > 10 ){
    // Set to false
    $passed = false;
    // Display a message
     wc_add_notice( __( "Sorry, You can’t have more than 10 bags in your cart.", "woocommerce" ), 
"error" );
}
return $passed;
}

现在,我们只需要添加一个条件即可限制用户(并显示警告),只要他们尝试增加其购物车数量(介于6到9袋之间)即可。

问题是,例如,某个客户在购物车中添加了5个行李,然后又回去尝试添加另一个行李怎么办?

我想避免这种情况,因此客户只能购买上述数量。

请检查此链接以更好地了解情况: https://mettaatta.com/product/metta-atta

1 个答案:

答案 0 :(得分:2)

这个:

if($cart_items_count >= 10 || $total_count > 10 ){
    // Display a message
}
if($total_count >=6 && $total_count <=9){
   // Display a message
}

将根据需要工作。

编辑

如果要合并它们:

if(($cart_items_count >= 10 || $total_count > 10) || ($total_count >=6 && $total_count <=9)){
   // Display a message
}