2
votes

I am looking for a Woocommerce hook that will help to change the discount percentage based on 2 different product category restrictions when a specific coupon is applied.

For example if customer add a specific coupon I will like to:

If a cart item is from product category A then it will give 10% discount on that item. if it's in product category B it will give 20% discount on that item

I've found this code but it's still get coupon discount from Coupons in WooCommerce.

add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 20, 5 );
function alter_shop_coupon_data( $round, $discounting_amount, $cart_item, $single, $coupon ){

    ## ---- Your settings ---- ##

    // Related coupons codes to be defined in this array (you can set many)
    $coupon_codes = array('10percent');

    // Product categories at 20% (IDs, Slugs or Names)  for 20% of discount
    $product_category20 = array('hoodies'); // for 20% discount

    $second_percentage = 0.2; // 20 %

    ## ---- The code: Changing the percentage to 20% for specific a product category ---- ##

    if ( $coupon->is_type('percent') && in_array( $coupon->get_code(), $coupon_codes ) ) {
        if( has_term( $product_category20, 'product_cat', $cart_item['product_id'] ) ){
            $original_coupon_amount = (float) $coupon->get_amount();
            $discount = $original_coupon_amount * $second_percentage * $discounting_amount;
            $round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
        }
    }
    return $round;
}
1
Maybe you need to update your cart? Not sure if this helps. And maybe the hook is wrong and you need to hook into your cart update or something like this.Mr. Jo

1 Answers

1
votes

This hook get's triggered of your cart get's updated. So maybe this is the correct hook. Try to fit your code within the foreach. If you need more help, let me know.

add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ) {

    $applied_coupons = WC()->cart->get_applied_coupons();

    if ( count( $applied_coupons ) > 0 ) {
        foreach ( $applied_coupons as $coupon ) {
            $round = .....
        }

        $cart_subtotal = WC()->cart->get_cart_subtotal();
        $new_value     = $cart_subtotal - $round;

        WC()->cart->set_total( $new_value );

        if ( $cart_updated ) {
            // Recalc our totals
            WC()->cart->calculate_totals();
        }
    }
}