Create Coupons Programmatically
The inspiration for this tutorial was another tutorial I found on the internet where it was recommended to create WooCommerce coupons using the wp_insert_post() function and update_post_meta(). When working with WooCommerce data since the 3.0 version it is always recommended to use CRUD objects. Coupons are not an exception.
In this tutorial, I will show you how to create a coupon programmatically in code using two methods – the WC_Coupon object and the REST API. Plus, as a bonus, I will show you how to generate coupon codes programmatically.
All right, let’s do it and begin with something simple.
Create Coupons Using CRUD (WC_Coupon)
This method I also use in my Simple Multisite Crossposting plugin, because it allows us to sync coupons between stores in a WooCommerce multisite network.
$coupon = new WC_Coupon();
$coupon->set_code( 'blackfrd' ); // Coupon code
$coupon->set_amount( 200 ); // Discount amount
$coupon->save();As you could’ve guessed, two methods set_code() and set_amount() are more than enough to create a coupon.

As simple as that. The only thing you have to double-check before using this code is that WooCommerce is loaded, otherwise, you will get “Fatal error: Uncaught Error: Class ‘WC_Coupon’ not found in blah blah.” Just consider using plugins_loaded action hook if you’re going to create a coupon in your custom plugin.
With that – done! What about some coupon configurations now?

Let’s create another coupon right now and configure everything like on the screenshot.
/**
* Create a Coupon Programmatically
*
* @author Misha Rudrastyh
* @url https://rudrastyh.com/woocommerce/create-coupon-programmatically.html
*/
$coupon = new WC_Coupon();
$coupon->set_code( 'ny_eve_2025' );
$coupon->set_description( 'Some coupon description.' );
// General tab
// discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_discount_type( 'percent' );
// discount amount
$coupon->set_amount( 20 );
// allow free shipping
$coupon->set_free_shipping( true );
// coupon expiry date
$coupon->set_date_expires( '31-12-2025' );
// Usage Restriction
// minimum spend
$coupon->set_minimum_amount( 1000 );
// maximum spend
$coupon->set_maximum_amount( 50000 );
// individual use only
$coupon->set_individual_use( true );
// exclude sale items
$coupon->set_exclude_sale_items( true );
// products
$coupon->set_product_ids( array( 132 ) );
// exclude products
$coupon->set_excluded_product_ids( array( 15, 16 ) );
// categories
$coupon->set_product_categories( array( 17 ) );
// exclude categories
$coupon->set_excluded_product_categories( array( 19, 20 ) );
// allowed emails
$coupon->set_email_restrictions(
array(
'no-reply@rudrastyh.com',
)
);
// Usage limit tab
// usage limit per coupon
$coupon->set_usage_limit( 100 );
// limit usage to X items
$coupon->set_limit_usage_to_x_items( 10 );
// usage limit per user
$coupon->set_usage_limit_per_user( 2 );
$coupon->save();The only thing I would like to highlight here is that you can also pass variation IDs in set_product_ids() and set_excluded_product_ids() methods.
Creating Coupons Using the WooCommerce REST API
Using the REST API technically is also a way of creating coupons programmatically, so let’s take a look at this method.
It is usually useful when you need to create a coupon on “Store 2” from “Store 1” or even from another application.
In this example, I am going to use the official WooCommerce PHP library for the REST API, more about it you can read in my other tutorial. So, let’s assume, that you already have the API initiated and the $woo_api variable is available.
Let’s create the same coupon we created in the previous example now!
$woo_api->post(
'coupons',
array(
'code' => 'ny_eve_2025',
'description' => 'Some coupon description.',
// General tab
'discount_type' => 'percent',
'amount' => 20,
'free_shipping' => true,
'date_expires' => '31-12-2025',
// Usage Restriction
'minimum_amount' => 1000,
'maximum_amount' => 50000,
'individual_use' => true,
'exclude_sale_items' => true,
//'product_ids' => array( 132 ),
//'excluded_product_ids' => array( 15, 16 ),
//'product_categories' => array( 17 ),
//'excluded_product_categories' => array( 19, 20 ),
'email_restrictions' => array( 'no-reply@rudrastyh.com' ),
// Usage limit tab
'usage_limit' => 100,
'limit_usage_to_x_items' => 10,
'usage_limit_per_user' => 2,
)
);There is a pretty good reason why I commented product_ids, excluded_product_ids, product_categories, and excluded_product_categories arguments. I did so in order for you to pay attention that you need to pass IDs of products/product categories on the target site to these parameters.
Generate Coupon Codes Programmatically
There are actually different ways how you can generate a random string in WordPress that can be used as a coupon code, for example:
strtolower( wp_generate_password( 8, false ) ),bin2hex( random_bytes( 4 ) ),substr( str_shuffle( 'ABCDEFGHJKMNPQRSTUVWXYZ23456789' ), 0, 8 )(similar to a WooCommerce way of generating coupon codes).
Let’s assume that we need to generate 100 random coupons, how can we achieve that?
// we can also apply the standard WooCommerce filters here
$chars = apply_filters( 'woocommerce_coupon_code_generator_characters', 'ABCDEFGHJKMNPQRSTUVWXYZ23456789' );
$length = apply_filters( 'woocommerce_coupon_code_generator_character_length', 8 );
// let's crate a loop for total amount of coupons that need to be generated
for ( $i = 1; $i <= 100 ; $i++ ) {
// use any method described above to generate a coupon code
// if this coupon code exists we need to try a new code
do {
$code = substr( str_shuffle( $chars ), 0, $length );
} while ( wc_get_coupon_id_by_code( $code ) );
// creating a coupon
$coupon = new WC_Coupon();
$coupon->set_code( $code );
$coupon->set_description( "Coupon code generated programmatically ({$i}/100)" );
$coupon->set_discount_type( 'percent' );
$coupon->set_amount( 20 );
$coupon->set_individual_use( true );
$coupon->set_usage_limit_per_user( 1 );
$coupon->save();
}Once you run this code, your “Coupons” page may look like this:

Misha Rudrastyh
Hey guys and welcome to my website. For more than 15 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
You are my hero :-) I created a php script for bulk generating coupons, now I’m writing a wp-cli command for it.
;)
Hello, Misha! First of all, thanks for your blog.
I added this code with Code Snippets Plugin and it generated a critical error. I solved it with the safe mode.
Do you know why this code generates that error? I tried the simple version of only 4 lines and it happens again.
Thanks again
Hello Alex,
It is because this code is not just for
functions.php;)Why is not for functions.php? If I create a plugin, it will work, right?
Absolutely great, thank you
Thanks, I was using the
wp_insert_post()method before, but this is better and easier.