Search code examples
phpwordpresswoocommercecoupon

Set Coupon used_by Customer ID manually


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'] );

Solution

  • 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.