Answer a question

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

Answers

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.

Logo

WooCommerce社区为您提供最前沿的新闻资讯和知识内容

更多推荐