【问题标题】:How to delete a coupon using api and coupon code in WooCommerce如何在 WooCommerce 中使用 api 和优惠券代码删除优惠券
【发布时间】:2020-01-24 06:23:03
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你在哪里使用rest api?它在wordpress中吗? WooCommerce 是同一个网站吗?你可以在你的 WooCommerce 所在的 functions.php 中添加代码吗?基本上,我需要知道你打算如何移除优惠券。
  • 嗨,我在 Larave 中使用 rest api。我找到了方法。

标签: php wordpress woocommerce woocommerce-rest-api coupon


【解决方案1】:

我可以像这样删除优惠券。我找到了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();
    

    试试这个

    【讨论】:

      【解决方案3】:

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

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

      谢谢

      【讨论】:

        最近更新 更多