Search the site:

How to Create Unique Coupon Codes in WooCommerce programmatically

In our previous post, we discussed how one can apply the coupon code automatically to the WooCommerce cart. There we used a generic coupon code which is created under the WooCommerce -> Coupons menu for all the orders placed by the different customers.

But sometimes as a store owner, you do want to create a unique coupon code for each customer on your website for certain situations. Let us take two examples where you may want to create unique coupon codes.

Example 1:

As an online store owner, the worst thing you can face with the purchase cycle of a customer is shopping cart abandonment. Approx. 68 to 70% of carts on a website are abandoned by users and there can be multiple reasons for that. One of the most common reasons would be the higher prices of the products or the additional charges like shipping charges are high which is shown generally at the checkout and not before that.

So here, to minimize the cart abandonment and convert as many users to customers, you can simply attract them with some discount coupons for their purchase. This way you can convert your abandoned carts to recovered carts.

In such cases, it is best to provide a unique coupon code with a single usage limit for each abandoned cart to avoid multiple usages of the code.

Example 2:

Another example of creating unique coupon codes would be for the customers who have purchased once from your store, but to attract them to purchase more you will prefer to send them some discount coupons for their next purchase. So here if you will create a generic coupon code for all the customers, they can pass on the coupons to the other people they know which can be used by them for their new purchases.

So here a coupon code that is created for returning customers can be misused. To avoid this, it is better to create a unique coupon code for each customer with a usage limit set to 1.

It is not feasible to create unique coupon codes manually for each customer from the WooCommerce -> Coupons menu. So the other option would be adding a code snippet for creating multiple coupons at a time for different users and we will be discussing how to achieve that in our post.

2 ways to create unique coupon codes in WooCommerce

The first step for creating a unique coupon code would be creating a random string for each coupon. That would be created using the below code.

$characters = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
$char_length = "8";
$random_string = substr( str_shuffle( $characters ),  0, $char_length );

Here the substr() function returns the portion of the string specified by the start and length parameters and str_shuffle() function randomly shuffles the string passed.

After generating the unique string, the next step would be creating the coupon code using a code snippet. We will be discussing 2 ways using which you can create coupon codes programmatically in WooCommerce.

1. Using wp_insert_post() function

The first way to add the coupon code programmatically is by using the wp_insert_post() function which allows you to add or update a WordPress post. So in our case, we are adding a post with post type shop_coupon using this function. To add the meta for the coupons created the update_post_meta() function is used. You need to add the below code to the functions.php file of the child theme or using any code snippets plugin.

$coupon_code = 'UNIQUECODE'; // Code created using the random string snippet.
$amount = '10'; // Amount
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

2. Using WooCommerce Rest API

Another way for adding coupon code programmatically is by using the WooCommerce Rest API provided by the plugin itself. WooCommerce has a complete guide provided for the Rest API including Authentication, Fetching Data, Coupons, Orders, etc. but for a reference, below is a small snippet that you can use for coupon code creation.

require_once __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;

$woocommerce = new Client(
            'wp_api' => true,
      'version' => 'wc/v3'

$data = [
    'code' => '10off',
    'discount_type' => 'percent',
    'amount' => '10',
    'individual_use' => true,
    'exclude_sale_items' => true,
    'minimum_amount' => '100.00'
$woocommerce->post( 'coupons', $data );

This is a basic code snippet for creating a coupon code for 10% off on an order which has order total more than $100. The coupon code is ’10off’ and can be used only by one customer. These are just the basic properties required for the coupon code creation, but if you want to add some additional properties, here is the list for it.

id(int) Unique identifier for the object.

code – (string)(Required) Coupon code.

amount – (string) The amount of discount. Should always be numeric, even if setting a percentage.

date_created – (date-time) The date the coupon was created, in the site’s timezone.

date_created_gmt – (date-time) The date the coupon was created, as GMT.

date_modified – (date-time) The date the coupon was last modified, in the site’s timezone.

date_modified_gmt – (date-time) The date the coupon was last modified, as GMT.

discount_type – (string) Determines the type of discount that will be applied. Options: percent, fixed_cart, and fixed_product. Default is fixed_cart.

description – (string) Coupon description.

date_expires – (string) The date the coupon expires, in the site’s timezone.

date_expires_gmt – (string) The date the coupon expires, as GMT.

usage_count – (int) Number of times the coupon has been used already.

individual_use – (bool) If true, the coupon can only be used individually. Other applied coupons will be removed from the cart. Default is false.

product_ids – (array) List of product IDs the coupon can be used on.

excluded_product_ids – (array) List of product IDs the coupon cannot be used on.

usage_limit  – (int) How many times the coupon can be used in total.

usage_limit_per_user  – (int) How many times the coupon can be used per customer.

limit_usage_to_x_items  – (int) Max number of items in the cart the coupon can be applied to.

free_shipping – (bool) If true and if the free shipping method requires a coupon, this coupon will enable free shipping. Default is false.

product_categories – (array) List of category IDs the coupon applies to.

excluded_product_categories – (array) List of category IDs the coupon does not apply to.

exclude_sale_items – (bool) If true, this coupon will not be applied to items that have sale prices. Default is false.

minimum_amount – (string) Minimum order amount that needs to be in the cart before coupon applies.

maximum_amount – (string) Maximum order amount allowed when using the coupon.

email_restrictions – (array) List of email addresses that can use this coupon.

used_by – (array) List of user IDs (or guest email addresses) that have used the coupon.

meta_data – (array) Metadata.


The code snippets mentioned above are just an example of how to create the coupon code. To use them on your website it needs to be attached to any hooks or filters which is required. For example, it can be used on any hook on the cart while you are tracking the cart abandonment or it can be used in the Cron job which will be run every week to send email updates to your customers.

Take advantage of unique coupon codes and make some happy returning customers for your website.

Browse more in: Code Snippets, WooCommerce Guide, WooCommerce How Tos, WooCommerce Tutorials
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Inline Feedbacks
View all comments
25 days ago

Can this be used with Klaviyo to automatically send individual codes in a welcome series?

from purchased

Subscribe for more offers

Would love your thoughts, please comment.x