Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shameemreza/5abdc52a44822c264c51ac8c5b009195 to your computer and use it in GitHub Desktop.
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.
/**
* 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