Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add conditionally a discount programmatically to Woocommerce 3

I'm looking for a way to create a coupon programmatically during the checkout and delete it when the checkout is done. This needs to be done base on a bonus system where I check if the customer is allowed to have a bonus or not. The important thing is, that I don't want to make it as a normal coupon because customers shouldn't be able to append it by there own knowing the code.

I've only found solution to append a coupon or create it programmatically. I've found nothing about a temporary coupon during one checkout.

It's also important that this coupon can be combined with just one another coupon and not more.

This is my code:

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

by the discount percentage }

So is this even possible?

like image 862
Mr. Jo Avatar asked Dec 25 '18 22:12

Mr. Jo


1 Answers

To get something simple you could use a negative fee instead (where each step points increase the discount percentage) like:

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

Code goes in function.php file of your active child theme (or active theme). Tested and works.

like image 169
LoicTheAztec Avatar answered Sep 26 '22 00:09

LoicTheAztec