Progressive percent discount based on cart amount

2019-07-10 00:07发布

I am trying to make a simple discount code for WooCommerce that gives you a percent discount before buying. Lets say that if you add products worth $100 you get 2% discount and if you add products worth $250 you get 4%, etc.

The only thing I found was this:

// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}

But could not manage to make it work with the modifying the hooks with those for the price.

How can I achieve this?

Thanks.

1条回答
相关推荐>>
2楼-- · 2019-07-10 00:48

Here is the way to do it using conditions based on cart subtotal excl tax amount to add this progressive percentage as a negative fee, so a discount:

add_action( 'woocommerce_cart_calculate_fees','cart_price_progressive_discount' );
function cart_price_progressive_discount() {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $has_discount = false;
    $stotal_ext = WC()->cart->subtotal_ex_tax;

    // Discount percent based on cart amount conditions
    if( $stotal_ext >= 100 && $stotal_ext < 250  ) {
        $percent = -0.02;
        $percent_text = ' 2%';
        $has_discount =true;
    } elseif( $stotal_ext >= 250  ) {
        $percent = -0.04;
        $percent_text = ' 4%';
        $has_discount =true;
    } 
    // Calculation
    $discount = $stotal_ext * $percent;

    // Displayed text
    $discount_text = __('Discount', 'woocommerce') . $percent_text;

    if( $has_discount ) {
        WC()->cart->add_fee( $discount_text, $discount, false );
    }
    // Last argument in add fee method enable tax on calculation if "true"
}

This goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


Similar: WooCommerce - Conditional Progressive Discount based on number of items in cart

Reference: WooCommerce class - WC_Cart - add_fee() method

查看更多
登录 后发表回答