In this tutorial, you are going to learn how to create discount coupons programmatically in WooCommerce. You can easily achieve this by using the WC_Coupon class. Let’s walk through the process with a simple example.
Here is the code snippet:
$coupon = new WC_Coupon();
$coupon->set_code( 'blackfriday' );
$coupon->set_amount( 20 );
$coupon->set_description( 'coupon description here.' );
$coupon->set_discount_type( 'percent' );
$coupon->set_date_expires( '31-12-2024' );
$coupon->save();
$coupon->set_code( 'blackfriday' );
$coupon->set_amount( 20 );
$coupon->set_description( 'coupon description here.' );
$coupon->set_discount_type( 'percent' );
$coupon->set_date_expires( '31-12-2024' );
$coupon->save();
- Use set_code() to define coupon code
- Use set_amount() to define discount amount
- Use set_description() to define discount description
- Use set_discount_type to define fixed or percentage discount
- Use set_date_expires to define the expiry date of coupon