How to Create Coupons Programmatically in WooCommerce

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();
 

 

  • 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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!