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

在我的自定义 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

 } }}

?>

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


扬帆大鱼
浏览 131回答 2
2回答

饮歌长啸

要将数量限制为 1,您将使用 WC_cartset_quantity()方法,如下所示:<?php&nbsp;$current_product_id = 5; // The product ID&nbsp;$cart&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= WC()->cart; // The WC_Cart Object// When cart is not empty&nbsp;if ( ! $cart->is_empty() ) {&nbsp; &nbsp; // Loop through cart items&nbsp; &nbsp; foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {&nbsp; &nbsp; &nbsp; &nbsp; // If the cart item is not the current defined product ID&nbsp; &nbsp; &nbsp; &nbsp; if( $current_product_id != $cart_item['product_id'] ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $cart->remove_cart_item( $cart_item_key ); // remove it from cart&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // If the cart item is the current defined product ID and quantity is more than 1&nbsp; &nbsp; &nbsp; &nbsp; elseif( $cart_item['quantity'] > 1 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $cart->set_quantity( $cart_item_key, 1 ); // Set the quantity to 1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}?>它应该有效。

米脂

对于任何希望无需代码即可实现相同功能的人。您只需在产品的库存设置中选择“单独出售”复选框,您也可以使用如下代码来实现此目的:update_post_meta($product_id, '_sold_individually', 'yes');
打开App,查看更多内容
随时随地看视频慕课网APP