1

I have the following function, I want it fire every time an order for a subscription is created.

I then want it to remove the store credit coupons from the parent subscription (as renewal orders will contain the coupon).

I'm getting the error:

"PHP message: PHP Fatal error: Uncaught Error: Call to undefined method WC_Order_Item_Coupon::get_discount_type()".

Where am I going wrong?

Is it passing in the parent subscription item in the right way?

   function remove_store_credit($subscription) {
    
      $coupons = $subscription->get_items( 'coupon' );
      foreach ( $coupons as $coupon ) {
        if($coupon->get_discount_type() == "smart_coupon"){
          $subscription->remove_coupon( $coupon->get_code() );
        }
      }
    
    }
    add_action('woocommerce_subscription_payment_complete','remove_store_credit',10,1);
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Rob
  • 6,304
  • 24
  • 83
  • 189

1 Answers1

2

The method get_discount_type() belongs to WC_Coupon Class but not to WC_Order_Item_Coupon Class.

So try you need to get an instance object of the WC_Coupon inside the coupon items foreach loop.

function remove_store_credit( $subscription ) {
    // Loop through order coupon items
    foreach ( $subscription->get_items( 'coupon' ) as $item ) {
        $coupon = new WC_Coupon( $item->get_code() ); // get an instance of the WC_Coupon Object 

        if( $coupon->get_discount_type() == "smart_coupon" ){
            $subscription->remove_coupon( $item->get_code() );
        }
    }
}
add_action('woocommerce_subscription_payment_complete', 'remove_store_credit', 10, 1);

It should solve this error.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Ah of course! Thanks for pointing it out, that works now – Rob Feb 04 '21 at 10:26
  • Is there a way to set the coupon usage to 1? I've put this in the if statement but it doesn't seem to change the usage `update_post_meta( $coupon->get_id(), 'usage_count', '1' );` – Rob Feb 04 '21 at 10:48
  • 1
    @Rob one by user or one at all? – LoicTheAztec Feb 04 '21 at 10:49
  • One at all, they're tied to a specific user by email address anyways so it just needs to change to 1 after use. It has 1 already set on the limit but when the order is going through it's not counting against a use, set if I can set that as a fallback. – Rob Feb 04 '21 at 10:51
  • 1
    Better try to use from `$coupon` variable *(the WC_Coupon Object instance)*: `$coupon->decrease_usage_count();` and `$coupon->save();` – LoicTheAztec Feb 04 '21 at 11:11
  • 1
    I tried that one but misunderstood it's use... that worked, thanks again – Rob Feb 04 '21 at 11:18