Create multiple coupons programmatically in WooCommerce 3+
Your code is not applying (or adding a coupon)… It's "creating" a new coupon!.
since WooCommerce 3, your code is a bit outdated. Instead you should better use the available WC_Coupon
setter methods like in the code below.
As you are generating the coupon code name with wp_generate_password()
function, you need to check that the new generated coupon code doesn't exist yet, as WooCommerce requires that each coupons code name is unique (see below a custom function for that purpose).
To generate multiple
coupons, you can just make a foreach loop that will iterate through a defined array of coupons costs.
1). First a utility function to generate unique non existing coupon names (coupon codes):
// Utility function that generate a non existing coupon code (as each coupon code has to be unique)function generate_coupon_code() { global $wpdb; // Get an array of all existing coupon codes $coupon_codes = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon'"); for ( $i = 0; $i < 1; $i++ ) { $generated_code = strtolower( wp_generate_password( 15, false ) ); // Check if the generated code doesn't exist yet if( in_array( $generated_code, $coupon_codes ) ) { $i--; // continue the loop and generate a new code } else { break; // stop the loop: The generated coupon code doesn't exist already } } return $generated_code;}
Code goes in functions.php
file of your active child theme (or active theme).
2). Now the code with the foreach loop WC_Coupon
setter methods to generate multiple coupons based on a defined array of coupon discount amounts (replaced non existing 'store_credit' coupon type by 'fixed_cart'):
// Here below define your coupons discount amount$discount_amounts = array( 12, 18, 15, 10 );// Set some coupon data by default$date_expires = date('Y-m-d', strtotime('+371 days'));$discount_type = 'fixed_cart'; // 'store_credit' doesn't exist// Loop through the defined array of coupon discount amountsforeach( $discount_amounts as $coupon_amount ) { // Get an emty instance of the WC_Coupon Object $coupon = new WC_Coupon(); // Generate a non existing coupon code name $coupon_code = generate_coupon_code(); // Set the necessary coupon data (since WC 3+) $coupon->set_code( $coupon_code ); $coupon->set_discount_type( $discount_type ); $coupon->set_amount( $coupon_amount ); $coupon->set_date_expires( $date_expires ); $coupon->set_usage_limit( 1 ); $coupon->set_individual_use( true ); // Create, publish and save coupon (data) $coupon->save();}
Tested and works.
Notes:
- "expiry_date" property is replaced by "date_expires"
apply_before_tax
property doesn't exist anymore- "free_shipping" is always set to
false
(no) by default