首页 > 解决方案 > 不允许在购物车中添加特定的产品数量

问题描述

我们希望客户只购买以下数量。

至今; 我们已经成功地限制了可以在单个产品页面上选择的数量,

我们目前正在使用以下代码将用户限制为总共 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

标签: phpwoocommerceconditional-statementscartcheckout

解决方案


这个 :

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
}

推荐阅读