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

问题描述 投票:1回答:3

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

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

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

并且当使用优惠券代码时,我需要手动将其删除。但是根据API documentation,我只能使用ID删除优惠券。但是目前使用优惠券代码时,我不知道ID。那么,有什么方法可以使用优惠券代码删除优惠券? 或者我可以从代码中检索ID

php wordpress woocommerce woocommerce-rest-api coupon
3个回答
1
投票

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

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

谢谢


0
投票
$coupon_code = '10perdiscount';

$cpn = new WC_Coupon($coupon_code);

echo $cpn->get_id();

尝试一下


0
投票

我可以这样删除优惠券。我找到了它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);
© www.soinside.com 2019 - 2024. All rights reserved.