繁体   English   中英

如何在 WooCommerce 中使用 api 和优惠券代码删除优惠券

[英]How to delete a coupon using api and coupon code in WooCommerce

在 WooCommerce 中,我创建了一个这样的优惠券。

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

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

而使用优惠券代码时,我需要手动删除它。 但是根据 API 文档,我只能使用 id 删除优惠券。 但是在使用优惠券代码的那一刻,我不知道id。 那么,有没有使用优惠券代码删除优惠券的方法呢? 或者我可以从代码中检索 id吗?

我可以像这样删除优惠券。 我在这里找到

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

尝试这个

这是我关于删除优惠券的工作代码。

$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'; 
}

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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