简体   繁体   中英

How to delete a coupon using api and coupon code in WooCommerce

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 ?

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);
$coupon_code = '10perdiscount';

$cpn = new WC_Coupon($coupon_code);

echo $cpn->get_id();

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM