Reputation: 145
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?
Upvotes: 1
Views: 860
Reputation: 11841
$coupon_code = '10perdiscount';
$cpn = new WC_Coupon($coupon_code);
echo $cpn->get_id();
Try this way - You can get ID from code like this.
Upvotes: -1
Reputation: 145
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);
Upvotes: 1
Reputation: 446
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
Upvotes: 0