Search code examples
phpwordpresswoocommercecartcoupon

WooCommerce specific coupon discount based on product category


I've a problem with this code to apply different percentage of discount to product in different category

The function work but is execute n times where n depends on the number of products in cart

add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 1, 5 );
function alter_shop_coupon_data( $discount, $discounting_amount, $cart_item, $single, $instance ){
    $coupons = WC()->cart->get_coupons();
    $cart_items = WC()->cart->get_cart();

    foreach ( $coupons as $code => $coupon ) {
        if ( $coupon->discount_type == 'percent' && $coupon->code == 'newsite' ) {
            foreach ($cart_items as $cart_item){
                $product_id = $cart_item['data']->id;                 
                
                if( has_term( 'cat1', 'product_cat', $product_id ) ){
                    $quantity = $cart_item['quantity'];
                    $price = $cart_item['data']->price;
                    $discount_20 = 0.2 * ($quantity * $price); //  20%

                }else{
                    $quantity = $cart_item['quantity'];
                    $price = $cart_item['data']->price;
                    $discount_10 = 0.1 * ($quantity * $price); //10%
                }
            }
        }
    }
    $discounting_amount = ($discount_20 + $discount_10);
    return $discounting_amount;
}

Solution

  • Since WooCommerce 3, there are many mistakes in your code… Also the $cart_item argument is included in the function, so you don't need to loop through cart items.

    Also note that $coupon->is_type('percent') (coupon type) is not needed as you target a specific coupon in your code: $coupon->get_code() == 'newsite.

    Try the following:

    add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 100, 5 );
    function alter_shop_coupon_data( $discount, $discounting_amount, $cart_item, $single, $instance ){
        // Loop through applied WC_Coupon objects
        foreach ( WC()->cart->get_coupons() as $code => $coupon ) {
            if ( $coupon->is_type('percent') && $coupon->get_code() == 'newsite' ) {
                $discount = $cart_item['data']->get_price() * $cart_item['quantity'];
     
                if( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) ){
                    $discount *= 0.2; // 20%
                }else{
                    $discount *= 0.1; // 10%
                }
            }
        }
        return $discount;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should better work.