首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WooCommerce :自动多次使用相同的优惠券

WooCommerce :自动多次使用相同的优惠券
EN

Stack Overflow用户
提问于 2017-08-06 16:19:59
回答 1查看 625关注 0票数 0

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

  • 每次x项目在购物车=>申请适当的优惠券。

例如:

  • 如果这位作者的3本书=> -5欧元在购物车上
  • 如果同一作者多出3本书(同样是其他书),=> -5欧元。
  • 等等(没有限制:如果订购了3,000本=> -15000欧元的书,它应该有效)

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

你知道这是否可能吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-07 01:31:38

与其使用优惠券,不如使用自定义折扣函数来实现此功能:

代码语言:javascript
复制
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文件中,或者在任何插件文件中。

这段代码是经过测试和工作的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45534059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档