Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.