I have come across
Coupon with 2 different percentage discounts based on product category in Woocommerce
Which shows how to alter % discounts for set categories. I want to implement a summer discount code on my store which gives £20 off to a selection of products.
The coupon code summer21 is set to apply a fixed product discount on only the following allowed product IDs
On 3 of the 4 a £20 discount should apply
But if the product ID = 119886, then only £10 should be discounted
I've tried modifying the code to the following, but unfortunately without the desired result. What am I missing?
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('Summer21');
// Product categories for only £10 discount (IDs, Slugs or Names)
$product_category10 = array('119886'); // for £10 discount
$second_discount = 10; // £10
## ---- The code: Changing the discount to £10 for specific products ---- ##
if ( $coupon->is_type('fixed_product') && in_array( $coupon->get_code(), $coupon_codes ) ) {
if( has_term( $product_category10, 'product_cat', $cart_item['product_id'] ) ){
$discount = $discounting_amount - $second_discount;
$round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
}
}
return $round;
}
This code also only changes the cart price, but does not show the correct display prices on the product pages.
Your code contains several mistakes
has_term() is not applicable, we are using in_array() insteadTo make this answer work, we apply some steps
First step, coupon settings:
Second step, settings inside the code function:
So you get:
function filter_woocommerce_coupon_get_discount_amount( $round, $discounting_amount, $cart_item, $single, $coupon ) {
// Related coupons codes to be defined in this array
$coupon_codes = array( 'summer21' );
// Product IDs, for second discount
$product_ids = array( 119886 );
// Second discount
$second_discount = 10;
// Changing the discount for specific product Ids
if ( $coupon->is_type('fixed_product') && in_array( $coupon->get_code(), $coupon_codes ) ) {
// Search for product ID in array product IDs
if ( in_array( $cart_item['product_id'], $product_ids ) ) {
// Get cart item quantity
$cart_item_qty = is_null( $cart_item ) ? 1 : $cart_item['quantity'];
// Discount
$discount = $coupon->get_amount() - $second_discount;
$discount = $single ? $discount : $discount * $cart_item_qty;
$round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
}
}
return $round;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );