WC_Abstract_Order::recalculate_coupons()
Apply all coupons in this order again to all line items.
Description Description
This method is public since WooCommerce 3.8.0.
Source Source
File: includes/abstracts/abstract-wc-order.php
public function recalculate_coupons() {
// Reset line item totals.
foreach ( $this->get_items() as $item ) {
$item->set_total( $item->get_subtotal() );
$item->set_total_tax( $item->get_subtotal_tax() );
}
$discounts = new WC_Discounts( $this );
foreach ( $this->get_items( 'coupon' ) as $coupon_item ) {
$coupon_code = $coupon_item->get_code();
$coupon_id = wc_get_coupon_id_by_code( $coupon_code );
// If we have a coupon ID (loaded via wc_get_coupon_id_by_code) we can simply load the new coupon object using the ID.
if ( $coupon_id ) {
$coupon_object = new WC_Coupon( $coupon_id );
} else {
// If we do not have a coupon ID (was it virtual? has it been deleted?) we must create a temporary coupon using what data we have stored during checkout.
$coupon_object = new WC_Coupon();
$coupon_object->set_props( (array) $coupon_item->get_meta( 'coupon_data', true ) );
$coupon_object->set_code( $coupon_code );
$coupon_object->set_virtual( true );
// If there is no coupon amount (maybe dynamic?), set it to the given **discount** amount so the coupon's same value is applied.
if ( ! $coupon_object->get_amount() ) {
// If the order originally had prices including tax, remove the discount + discount tax.
if ( $this->get_prices_include_tax() ) {
$coupon_object->set_amount( $coupon_item->get_discount() + $coupon_item->get_discount_tax() );
} else {
$coupon_object->set_amount( $coupon_item->get_discount() );
}
$coupon_object->set_discount_type( 'fixed_cart' );
}
}
/**
* Allow developers to filter this coupon before it get's re-applied to the order.
*
* @since 3.2.0
*/
$coupon_object = apply_filters( 'woocommerce_order_recalculate_coupons_coupon_object', $coupon_object, $coupon_code, $coupon_item, $this );
if ( $coupon_object ) {
$discounts->apply_coupon( $coupon_object, false );
}
}
$this->set_coupon_discount_amounts( $discounts );
$this->set_item_discount_amounts( $discounts );
// Recalculate totals and taxes.
$this->calculate_totals( true );
}
Changelog Changelog
| Version | Description |
|---|---|
| 3.2.0 | Introduced. |