【问题标题】:Add conditionally a discount programmatically to Woocommerce 3以编程方式有条件地向 Woocommerce 3 添加折扣
【发布时间】:2018-12-25 22:02:59
【问题描述】:

我正在寻找一种在结帐期间以编程方式创建优惠券并在结帐完成时将其删除的方法。这需要基于奖金系统来完成,在该系统中我检查客户是否被允许获得奖金。重要的是,我不想将其作为普通优惠券,因为客户不应该通过知道代码来附加它。

我只找到了附加优惠券或以编程方式创建优惠券的解决方案。我在一次结账时没有发现任何关于临时优惠券的信息。

此优惠券只能与另一张优惠券组合使用,这一点也很重要。

这是我的代码:

if ( get_discount_points() < 100 ) {
    //Customer has bonus status 1
} elseif ( get_discount_points() < 200 ) {
    //Customer has bonus status 2
} else {
    //Customer has bonus status x

按折扣百分比 }

那么这可能吗?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    为了简单起见,您可以改用负费用(每一步都会增加折扣百分比),例如:

    function get_customer_discount(){
        if( $points = get_discount_points() ){
            if ( $points < 100 ) {
                return 1; // 1 % discount
            } elseif ( $points < 200 ) {
                return 2; // 2.5 % discount
            } else {
                return 4; // 5 % discount
            }
        } else {
            return false;
        }
    }
    
    
    add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 10, 1 );
    function custom_discount( $cart ){
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Only for 2 items or more
        if( $percentage = get_customer_discount() ){
            $discount = WC()->cart->get_subtotal() * $percentage / 100;
    
            // Apply discount to 2nd item for non on sale items in cart
            if( $discount > 0 )
                $cart->add_fee( sprintf( __("Discount %s%%"), $percentage), -$discount );
        }
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2019-05-05
      • 2019-05-09
      • 2014-12-22
      • 2015-12-07
      • 2015-11-03
      • 2018-06-05
      相关资源
      最近更新 更多