【问题标题】:Cart add_fee() is not working in checkout page购物车 add_fee() 在结帐页面中不起作用
【发布时间】:2017-01-31 19:09:54
【问题描述】:

在 WooCommerce 中,我想在不使用优惠券的情况下进行折扣,折扣计算将基于产品价格,例如“以 2 的价格购买 3 个产品。

在我的活动主题的 function.php 中,我正在使用以下代码:

function promo () {
    if (is_cart()) {
        $woocommerce->cart->add_fee( __('des', 'woocommerce'), -50.00`enter code here`, true, '');
    }
 }
add_action ('woocommerce_cart_calculate_fees', 'promo');

我的问题:此代码在结帐页面上不起作用。
如果我强制审查订单,则会出现折扣,但总价值不会改变。我认为它没有节省费用。

我怎样才能使它工作(在结帐页面上)?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce checkout cart


    【解决方案1】:

    这个钩子是为购物车费用制作的(或折扣)所以你必须删除 if (is_cart()) {条件,那个为什么它不起作用……

    这是实现“买二送三”折扣的正确功能代码,它将根据订单项数量进行折扣:

    add_action('woocommerce_cart_calculate_fees' , 'discount_2_for_3', 10, 1);
    function discount_2_for_3( $cart_object ){
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Initialising variable
        $discount = 0;
    
        // Iterating through cart items
        foreach( $cart_object->get_cart() as $cart_item ){
    
            // Getting item data from cart object
            $item_id = $cart_item['product_id']; // Item Id or product ID
            $item_qty = $cart_item['quantity']; // Item Quantity
            $product_price = $cart_item['data']->price; // Product price
            $line_total = $cart_item['line_total']; // Price x Quantity total line item
    
            // THE DISCOUNT CALCULATION
            if($item_qty >= 3){
                // For each item quantity step of 3 we add 1 to $qty_discount
                for($qty_x3 = 3, $qty_discount = 0; $qty_x3 <= $item_qty; $qty_x3 += 3, $qty_discount++);
                $discount -= $qty_discount * $product_price;
            }
        }
    
        // Applied discount "2 for 3"
        if( $discount != 0 ){
            // Note: Last argument is related to applying the tax (false by default)
            $cart_object->add_fee( __('Des 2 for 3', 'woocommerce'), $discount, false);
        }
    
    }
    

    这适用于简单的产品,但不适用于产品变体……

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    代码已经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2016-09-29
      • 2020-08-06
      • 1970-01-01
      相关资源
      最近更新 更多