Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Create Unique Coupon Codes in WooCommerce Programmatically

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.

Creating unique coupon codes Use Case #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 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.

Creating unique coupon codes Use Case #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 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. Create WooCommerce Coupon Codes 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, 'date_expires', '1 May 2023' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

You need to save this snippet & select “Only run once” in the Code Snippets plugin. Once the snippet is saved, you can click on “Execute once” to run the code.

Create Unique Coupon Codes in WooCommerce programmatically

2. Create WooCommerce Coupon Codes using WooCommerce Rest API

Another way for adding coupon code programmatically in WooCommerce is by using the Rest API provided by the plugin itself. The WooCommerce Coupons API guide allows you to create, view, update, and delete coupon codes. For reference, below is a 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(
    'https://example.com',
    'consumer_key',
    'consumer_secret',
        [
            '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.

Related Article: How to Hide the WooCommerce Coupon code field based on specific products

Conclusion

The code snippets mentioned above are just an example of how to create a coupon programmatically in WooCommerce. 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. One such alternative is to create a coupon with WC_Coupon() object in WooCommerce that creates a single coupon.

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

Share It:

Subscribe
Notify of
4 Comments
Newest
Oldest
Inline Feedbacks
View all comments
Katie
2 years ago

Thanks. This was great. Except I had to change ‘expiry_date’ to ‘date_expires’ for it to work.
I was also able to use it with WooCommerce Subscriptions by changing the discount type to:
discount_type = ‘recurring_percent’;

Admin
1 year ago
Reply to  Katie

Thank you Katie. I have changed the code snippet to reflect date_expires. Earlier versions of WooCommerce had expiry_date as the meta key.

With the WooCommerce Subscriptions plugin, you were able to use the coupon on renewal orders as well with the discount_type = ‘recurring_percent’ option?

Sarah
2 years ago

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

Admin
1 year ago
Reply to  Sarah

Hi Sarah, Apologies for the late reply. To use this with Klaviyo, the above solution won’t work. I do see that many people need some solution for this. Currently though, Klaviyo only recommends to upload the WooCommerce coupons via a csv into their tool.

4
0
Would love your thoughts, please comment.x
()
x