【问题标题】:How to restrict WooCommerce cart item quantity to one for specific item如何将特定商品的 WooCommerce 购物车商品数量限制为一个
【发布时间】:2020-07-08 21:16:46
【问题描述】:

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

我的工作是 Empty cart upon page load allowing add to cart in WooCommerce 回答我之前的问题。

这就是我所拥有的:

 <?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
 } }}
?>

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

【问题讨论】:

  • 没有真正彻底阅读您的问题或代码。是否不能在产品库存选项中选中“如果此商品每个订单只能购买一次,则激活此选项”?
  • 那行得通。

标签: php wordpress woocommerce cart product-quantity


【解决方案1】:

要将数量限制为 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
        }
    }
}
?>

它应该可以工作。

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2021-05-16
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多