WC_Cart_Totals::sort_coupons_callback │ protected │ WC 1.0

Sort coupons so discounts apply consistently across installs.

In order of priority;

  • sort param
  • usage restriction
  • application position for sequential discounts
  • coupon value
  • ID

Method of the class: WC_Cart_Totals{}

No Hooks.

Returns

int.

Usage

// protected - for code of main (parent) or child class
$result = $this->sort_coupons_callback( $a, $b );
$a(WC_Coupon) (required)
Coupon object.
$b(WC_Coupon) (required)
Coupon object.

WC_Cart_Totals::sort_coupons_callback() code WC 11.2.2

protected function sort_coupons_callback( $a, $b ) {
	if ( $a->sort === $b->sort ) {
		if ( $a->get_limit_usage_to_x_items() === $b->get_limit_usage_to_x_items() ) {
			$a_position = $this->coupon_application_positions[ spl_object_id( $a ) ] ?? null;
			$b_position = $this->coupon_application_positions[ spl_object_id( $b ) ] ?? null;

			// Equal positions must fall through to the amount fallback, so the inequality check stays outside the helper.
			if ( null !== $a_position && null !== $b_position && $a_position !== $b_position ) {
				return wc_uasort_comparison( $a_position, $b_position );
			}

			if ( $a->get_amount() === $b->get_amount() ) {
				return $b->get_id() - $a->get_id();
			}
			return ( $a->get_amount() < $b->get_amount() ) ? -1 : 1;
		}
		return ( $a->get_limit_usage_to_x_items() < $b->get_limit_usage_to_x_items() ) ? -1 : 1;
	}
	return ( $a->sort < $b->sort ) ? -1 : 1;
}