如何将特定商品的 WooCommerce 购物车商品数量限制为一个

How to restrict WooCommerce cart item quantity to one for specific item

在我的自定义 Woocommerce 模板中,我想将产品数量限制为 1。

我正在 回答我之前的问题。

这是我的:

 <?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object
       $quantity = $cart_item['quantity'];//the quantity
// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        }
}
 if( $quantity >=1) {
    $cart->remove_cart_item( $cart_item_key ); // remove it from cart
 } }}
?>

有点管用。但我想在同一页面上结帐,使用此代码结帐不会在产品添加到购物车时更新。

要将数量限制为 1,您将这样使用 WC_cart set_quantity() 方法:

<?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object

// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        } 
        // If the cart item is the current defined product ID and quantity is more than 1
        elseif( $cart_item['quantity'] > 1 ) {
            $cart->set_quantity( $cart_item_key, 1 ); // Set the quantity to 1
        }
    }
}
?>

应该可以。