【问题标题】:Set quantity of product in WooCommerce cart programatically [duplicate]以编程方式设置 WooCommerce 购物车中的产品数量 [重复]
【发布时间】:2020-11-27 19:54:37
【问题描述】:

我有一个连接到woocommerce_before_calculate_totals 的函数,如果应用了特定的优惠券,它可以为人们提供特定产品的折扣。

我不希望人们通过更改项目的数量来滥用它,所以我希望始终将该项目的数量重置为 1。

这是我的代码:

add_action( 'woocommerce_before_calculate_totals', 'change_price_of_product' );


function change_price_of_product() {
    $items = WC()->cart->get_cart();
    $coupons = WC()->cart->applied_coupons;
    
    $only_one_gift = 0;
    
    if (in_array('getmygift', $coupons)) {
        
         foreach($items as $item) {
                if (isset($item['product_id'])) {
                    
                    if ($only_one_gift > 0) {
                        break;
                    }
                    
                    
                    if (($item['product_id']) == 5261) {
                        $only_one_gift++;
                        $item['data']->set_price( 0 );
                        // I WANT TO SET THE QUANTITY TO 1 HERE  
                    }
                }
            }
    }
}

如果我包含$item['data']->set_quantity(1);$item->set_quantity(1);,函数就会中断。

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: php wordpress woocommerce cart product-quantity


    【解决方案1】:

    想通了。

    必须将 foreach 编辑为 foreach($items as $cart_item_key => $item),然后使用 WC()->cart->set_quantity( $cart_item_key, 1 );

    这是完整的代码:

    add_action( 'woocommerce_before_calculate_totals', 'change_price_of_product' );
    
    
    function change_price_of_product() {
        $items = WC()->cart->get_cart();
        $coupons = WC()->cart->applied_coupons;
        
        $only_one_gift = 0;
        
        if (in_array('getmygift', $coupons)) {
            
             foreach($items as $cart_item_key => $item) {
                    if (isset($item['product_id'])) {
                        
                        if ($only_one_gift > 0) {
                            break;
                        }
                        
                        
                        if (($item['product_id']) == 5261) {
                            $only_one_gift++;
                            $item['data']->set_price( 0 );
                            WC()->cart->set_quantity( $cart_item_key, 1 );
                        }
                    }
                }
        }
    }
    

    【讨论】:

    • woocommerce_before_calculate_totals 包含参数$this 等于$cart,因此您可以改用$cart->set_quantity( $cart_item_key, 1 );。还有$cart->get_cart();$cart->get_applied_coupons();等...
    猜你喜欢
    • 2014-07-25
    • 2018-07-24
    • 1970-01-01
    • 2017-12-10
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多