Created
May 21, 2025 04:00
-
-
Save shameemreza/5abdc52a44822c264c51ac8c5b009195 to your computer and use it in GitHub Desktop.
Generates a unique coupon when a specific product (Bronze, Silver, or Gold Coupon) is purchased and emails it to the customer using AutomateWoo.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate a coupon when a specific product is purchased and email it to the customer. | |
* @param AutomateWoo\Workflow $workflow | |
*/ | |
function my_automatewoo_generate_coupon( $workflow ) { | |
$order = $workflow->data_layer()->get_order(); | |
if ( ! $order ) { | |
return; | |
} | |
foreach ( $order->get_items() as $item ) { | |
$product_name = $item->get_name(); | |
if ( $product_name === 'Bronze Coupon' ) { | |
$discount = 5; | |
$expiry_days = 30; | |
} elseif ( $product_name === 'Silver Coupon' ) { | |
$discount = 10; | |
$expiry_days = 90; | |
} elseif ( $product_name === 'Gold Coupon' ) { | |
$discount = 20; | |
$expiry_days = 180; | |
} else { | |
continue; | |
} | |
$coupon_code = strtolower( str_replace( ' ', '_', $product_name ) ) . '-' . wp_generate_password( 6, false ); | |
$coupon = new WC_Coupon(); | |
$coupon->set_code( $coupon_code ); | |
$coupon->set_discount_type( 'percent' ); | |
$coupon->set_amount( $discount ); | |
$coupon->set_date_expires( ( new DateTime( "+$expiry_days days", wp_timezone() ) )->format( 'Y-m-d' ) ); | |
$coupon->set_usage_limit( 1 ); | |
$coupon->set_email_restrictions( [ $order->get_billing_email() ] ); | |
$coupon->save(); | |
// Email the coupon code to the customer | |
wp_mail( | |
$order->get_billing_email(), | |
'Your Coupon Code', | |
'Here is your coupon code: ' . $coupon_code | |
); | |
// Only one coupon per order | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment