Skip to content

Instantly share code, notes, and snippets.

@PluginRepublicSupport
Last active October 27, 2023 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PluginRepublicSupport/5490be9425df4e116a30f9018659a3bb to your computer and use it in GitHub Desktop.
Save PluginRepublicSupport/5490be9425df4e116a30f9018659a3bb to your computer and use it in GitHub Desktop.
Exclude add-ons cost in coupon discounts
<?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 );
@PluginRepublicSupport
Copy link
Author

PluginRepublicSupport commented Oct 27, 2023

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment