亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將特定商品的 WooCommerce 購物車商品數量限制為一個

如何將特定商品的 WooCommerce 購物車商品數量限制為一個

PHP
揚帆大魚 2023-07-21 16:19:14
在我的自定義 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?} }}?>這有點管用。但我希望在同一頁面上結帳,并且使用此代碼將產品添加到購物車時結帳不會更新。
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

要將數量限制為 1,您將使用 WC_cartset_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

        }

    }

}

?>

它應該有效。


查看完整回答
反對 回復 2023-07-21
?
米脂

TA貢獻1836條經驗 獲得超3個贊

對于任何希望無需代碼即可實現相同功能的人。您只需在產品的庫存設置中選擇“單獨出售”復選框,您也可以使用如下代碼來實現此目的:update_post_meta($product_id, '_sold_individually', 'yes');



查看完整回答
反對 回復 2023-07-21
  • 2 回答
  • 0 關注
  • 193 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號