Generate a Batch of Unique Coupon Codes
Creates a set of single-use coupon codes in one go, for printed flyers, influencer campaigns or event giveaways, and lists them so you can copy them.
Opens WPIDE on
Code
$wpide_coupon_batch = array(
'count' => 25, // Coupons to create (max 500 per run).
'prefix' => 'FLYER-',
'type' => 'percent', // percent, fixed_cart or fixed_product.
'amount' => 15,
'expires' => '+90 days',
);
if ( ! class_exists( 'WC_Coupon' ) || ( ! current_user_can( 'manage_woocommerce' ) && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) ) {
return;
}
$wpide_codes = array();
for ( $i = 0; $i < min( 500, (int) $wpide_coupon_batch['count'] ); $i++ ) {
do {
$code = $wpide_coupon_batch['prefix'] . strtoupper( wp_generate_password( 8, false, false ) );
} while ( wc_get_coupon_id_by_code( $code ) );
$coupon = new WC_Coupon();
$coupon->set_code( $code );
$coupon->set_discount_type( $wpide_coupon_batch['type'] );
$coupon->set_amount( $wpide_coupon_batch['amount'] );
$coupon->set_usage_limit( 1 );
$coupon->set_date_expires( strtotime( $wpide_coupon_batch['expires'] ) );
$coupon->set_description( 'Generated batch ' . wp_date( 'Y-m-d' ) );
$coupon->save();
$wpide_codes[] = $code;
}
echo esc_html( implode( "\n", $wpide_codes ) );
Notes
Runs only when you press Run in the editor or use WP-CLI, so set the amount, type and expiry first.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.