Im editing a plugin for woocommerce that normally generates random coupon codes. but i needed it to generate them in order (000001, 000002, 000003, etc etc or 1, 2, 3, etc etc). but i cant make it work. ive messed around with if statements and everything. i’ll post what i have now and the original code.
My code now:
function wccg_get_random_coupon() {
// Generate unique coupon code
$random_coupon = '';
$length = 6;
$charset = '0123456789';
$count = strlen( $charset );
while ( $length-- ) {
for ($a = 0; $a <= $count; $a++) {
$random_coupon = implode( '-', str_split( strtoupper( $random_coupon ), 6 ) );
// Ensure coupon code is correctly formatted with WC Core filter
$coupon_code = apply_filters( 'woocommerce_coupon_code', $random_coupon );
// Additional filter that only executes for this plugin, not for other WC Core coupons
$random_code = apply_filters( 'woocommerce_coupon_generator_random_coupon_code', $coupon_code );
return $random_code;
} }
}
Original code:
function wccg_get_random_coupon() {
// Generate unique coupon code
$random_coupon = '';
$length = 12;
$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$count = strlen( $charset );
while ( $length-- ) {
$random_coupon .= $charset[ mt_rand( 0, $count-1 ) ];
}
$random_coupon = implode( '-', str_split( strtoupper( $random_coupon ), 4 ) );
// Ensure coupon code is correctly formatted with WC Core filter
$coupon_code = apply_filters( 'woocommerce_coupon_code', $random_coupon );
// Additional filter that only executes for this plugin, not for other WC Core coupons
$random_code = apply_filters( 'woocommerce_coupon_generator_random_coupon_code', $coupon_code );
return $random_code;
}