有条件地以编程方式向Woocommerce添加折扣 3.



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

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

同样重要的是,此优惠券可以仅与另一张优惠券结合使用,而不是更多。

这是我的代码:

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

按折扣百分比 }

那么这可能吗?

要获得简单的东西,您可以使用负费用代替(每一步积分都会增加折扣百分比),例如:

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 );
    }
}

代码进入函数.php活动子主题(或活动主题)的文件。经过测试并工作。

最新更新