skip to Main Content

In WooCommerce, I created a coupon like this.

$coupon_data = [
    'code' => $code,
    'amount' => '15',
];

$wooCommerceMRLiveV2 = WooCommerceConnection::wooCommerceMRLiveV2();
$retval2 = $wooCommerceMRLiveV2->post('coupons', $coupon_data);

And when the coupon code is used, I need to delete it manually.
But according to API documentation, I can only delete coupons using id. But at the moment when the coupon code is used, I don’t know the id.
So, is there any method to delete the coupon using coupon code? Or can I retrieve id from code?

3

Answers


  1. Chosen as BEST ANSWER

    I could delete the coupon like this. I found it here.

    $coupon_json = $wooCommerceV2->get('coupons', ['code'=>$coupon_code]);
    $coupon_arr = json_decode($coupon_json);
    $id = $coupon_arr[0]->id;
    $result = $wooCommerceV2->delete('coupons/'.$id);
    Log::info($result);
    

  2. $coupon_code = '10perdiscount';
    
    $cpn = new WC_Coupon($coupon_code);
    
    echo $cpn->get_id();
    

    Try this

    Login or Signup to reply.
  3. This is my working code about remove coupon.

    $order = wc_get_order($order_id);
    $get_previous_coupon = $order->get_used_coupons();
    if (count($get_previous_coupon) > 0 && is_array($get_previous_coupon)) {
        foreach( $order->get_used_coupons() as $applied_coupon_code ){
            $applied_coupon = $applied_coupon_code;
        }
        $order->remove_coupon( $applied_coupon );
        $code = 1;
        $message = 'Coupon successfully removed';
    }else{
        $code = 0;
        $message = 'error'; 
    }
    

    Thanks

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