Last active
October 27, 2023 08:59
-
-
Save PluginRepublicSupport/5490be9425df4e116a30f9018659a3bb to your computer and use it in GitHub Desktop.
Exclude add-ons cost in coupon discounts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Exclude add-ons cost in coupon discounts | |
* @return discount amount | |
*/ | |
add_filter( 'woocommerce_coupon_get_discount_amount', function( $amount, $discounting_amount, $cart_item, $single, $coupon ) { | |
$apply_coupon = array( '1097_1772' ); // GroupId_FieldId | |
if ( $cart_item['product_extras']['price_with_extras'] > 0 ) { | |
if ( $coupon->get_meta('discount_type') == 'percent' ) { | |
$percent_discount = $coupon->get_amount() / 100; | |
$amount = 0; | |
if ( count( $apply_coupon ) ) { | |
foreach ( $apply_coupon as $field ) { | |
list( $group_id, $field_id ) = explode( '_', $field ); | |
$amount += $cart_item['product_extras']['groups'][$group_id][$field_id]['price'] * $cart_item['quantity']; | |
} | |
} | |
$amount += $cart_item['product_extras']['original_price'] * $cart_item['quantity']; | |
$amount *= $percent_discount; | |
} | |
} | |
return $amount; | |
}, 10, 5 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The snippet overrides the coupon discount amount so that it exempts the add-ons costs from the computation. Currently, this only applies to percentage discounts.
If you want certain fields to add to the main product price before applying the discount, you can update this line:
$apply_coupon = array( '1097_1772' ); // GroupId_FieldId
Just specify the group ID and field ID as a single item. You can add more fields (comma-separated) like so:
$apply_coupon = array( '1097_1772', '2023_2024' ); // GroupId_FieldId
Otherwise, set the array empty so that the entire add-ons total is not included: $apply_coupon = array( );
An example:
Product price = 100
Field 1 (#1772) = 100
Field 2 (#2024) = 100
Field 3 (#2025) = 100
If you apply a 10% coupon discount, the discount amount will be 30 (Product price + Field 1 + Field 2).