【问题标题】:WooCommerce : auto apply the same coupon several timesWooCommerce:多次自动应用相同的优惠券
【发布时间】:2017-08-06 16:19:59
【问题描述】:

在 WooCommerce 中,我正在自动应用优惠券,但我找不到获得这种行为的方法:

  • 每次购物车中有 x 件商品 => 应用适当的优惠券。

例如:

  • 如果该作者的 3 本书 => -5€ 在购物车上
  • 如果同一作者的额外 3 本书(其他相同)=> -5€ 额外
  • 等。 (没有限制:如果订购 3000 本书应该可以工作 => -15000 欧元)

我使用 $wc->cart->add_discount($discount),但它返回“优惠券已申请”,因为第二组商品在购物车中。

你知道这是否可能吗?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce cart discount


    【解决方案1】:

    您最好使用自定义折扣功能,而不是使用优惠券:

    add_action( 'woocommerce_cart_calculate_fees', 'cart_item_discount_by3', 10, 1 );
    function cart_item_discount_by3( $cart_object ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // initializing and set variables
        $discount = 0;
        $by3 = 3; // each 3 item quantity
        $dicount_price_by3 = 5; // amout to discount each 3 items quantity
    
        // Iterating through each cart item
        foreach( $cart_object->get_cart() as $cart_item ):
            // Get the item quantity
            $qty = $cart_item["quantity"];
            // starting when  quantity is upto 3
            if($qty >= $by3):
                for($j = $by3, $k = 0; $j <= $qty; $j+=$by3, $k++);
                $discount += $dicount_price_by3 * $k;
                break;
            endif;
        endforeach;
    
        // Adding the discount (a negative fee)
        if ($discount > 0){
            $cart_object->add_fee( __( "Discount quantity", 'woocommerce'), -$discount, true );
            # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
    
            // Displaying a custom notice (optional)
            wc_clear_notices();
            wc_add_notice( __("You get a quantity discount on some items"), 'notice');
        }
    }
    

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

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

    【讨论】:

    • 谢谢!它工作得很好:)而且它比我正在研究的另一个解决方案更简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2022-10-19
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多