skip to Main Content

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


  1. Chosen as BEST ANSWER

    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() );
            }
          }
    

  2. The remove_coupon method parameter is the coupon code, not the object.

    Try this:

    $subscription->remove_coupon( 'coupon_code' );
    

    Where coupon_code is the name of the coupon that the customer applied to the cart or checkout.

    Here you will find the documentation: https://woocommerce.github.io/code-reference/files/woocommerce-includes-abstracts-abstract-wc-order.html#source-view.1187

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search