1

I am looking for a documentation regarding setting a coupon's used_by particular customer user_id on Woocommerce if coupon code to be added manually via REST API or from the Admin create new order endpoint. But I find no way to do it correctly. Hoping someone could point me out. Below is my code developed so far but it returned NULL.

$WC_Coupon = new WC_Coupon($request['code']);
$WC_Coupon->set_used_by( $request['customer_id'] );
mujuonly
  • 11,370
  • 5
  • 45
  • 75
Calvin Seng
  • 193
  • 1
  • 19

2 Answers2

0

Are you sure that your $WC_Coupon is instantiated properly? No matter how a coupon was added into the system, once it is there, it should act like any other coupon.

Would suggest you to take a var_dump of $WC_Coupon and see if it outputs a proper value otherwise, you might not be providing the constructor with a proper code parameter.

Abhishek
  • 55
  • 4
  • Yes. $WC_Coupon returns the ID of the coupon code. But set_used_by function just return empty value. I am just looking for a manual way to insert these data via backend. Not the usual checkout method. – Calvin Seng Apr 16 '20 at 04:29
  • Are you able to edit these coupons using the dashboard? And could you try to get the full dump of the coupon that you are trying to alter to see if something might be missing. Keeping all this in mind, I still don't think that once a coupon is created, it can pose any such issues as WordPress/WooCommerce are super flexible pieces software. – Abhishek Apr 16 '20 at 14:42
0

Found the answer...The right function to use is increase_usage_count instead of directly using the Coupon object to set the used_by meta key.

$WC_Coupon = new WC_Coupon($request['code']);
$used_by = $request['customer_id'];
$WC_Coupon->increase_usage_count( $used_by );

Hope this snippet helps whoever that creates order via REST API and in need of a method to track who has consumed the coupon code.

Calvin Seng
  • 193
  • 1
  • 19