Programmatically remove coupon from subscription/order

Viewed 139

How can I programmatically remove a coupon from a subscription/order?

This is what I've tried but when running it, it doesn't seem to remove the coupon, where am I going wrong?

    $subscription = new WC_Subscription( $_REQUEST['sub_id'] );
    $coupon_code = $_REQUEST['voucher_code'];
    $coupon = new WC_Coupon( $coupon_code );
    $subscription->remove_coupon( $coupon );

The flip side of that was adding a coupon which worked fine:

      $subscription->add_coupon( $coupon_code,$coupon_amount,'0' );
      $subscription->set_total( $subscription->get_total() - $coupon_amount );
      $subscription->save();
2 Answers

I found a way around this, I just needed to loop over each coupon:

      $coupons = $subscription->get_items( 'coupon' );

      // Remove the coupon line.
      $strcode = strtolower($coupon_code);
        foreach ( $coupons as $coupon ) {
        if($coupon->get_code() == $strcode){
          $subscription->remove_coupon( $coupon->get_code() );
        }
      }
Related