Unique Thank-You Coupon in the Order Completed Email
Creates a personal, single-use discount code for each completed order and adds it to the customer's "Order completed" email to encourage a second purchase.
Opens WPIDE on
Code
$wpide_thanks_coupon = array(
'type' => 'percent', // percent or fixed_cart.
'amount' => 10,
'days' => 60, // Days until it expires.
'prefix' => 'THANKS-',
);
add_action( 'woocommerce_order_status_completed', function ( $order_id, $order = null ) use ( $wpide_thanks_coupon ) {
$order = $order instanceof WC_Order ? $order : wc_get_order( $order_id );
if ( ! $order || $order->get_meta( '_wpide_thanks_coupon' ) || ! $order->get_billing_email() ) {
return;
}
$code = $wpide_thanks_coupon['prefix'] . strtoupper( wp_generate_password( 8, false, false ) );
$coupon = new WC_Coupon();
$coupon->set_code( $code );
$coupon->set_discount_type( $wpide_thanks_coupon['type'] );
$coupon->set_amount( $wpide_thanks_coupon['amount'] );
$coupon->set_usage_limit( 1 );
$coupon->set_individual_use( true );
$coupon->set_email_restrictions( array( $order->get_billing_email() ) );
$coupon->set_date_expires( time() + $wpide_thanks_coupon['days'] * DAY_IN_SECONDS );
$coupon->set_description( 'Thank-you coupon for order #' . $order->get_order_number() );
$coupon->save();
$order->update_meta_data( '_wpide_thanks_coupon', $code );
$order->save_meta_data();
}, 1, 2 );
add_action( 'woocommerce_email_after_order_table', function ( $order, $sent_to_admin, $plain_text, $email ) use ( $wpide_thanks_coupon ) {
$code = $order->get_meta( '_wpide_thanks_coupon' );
if ( $sent_to_admin || ! $code || ! $email || 'customer_completed_order' !== $email->id ) {
return;
}
$offer = 'percent' === $wpide_thanks_coupon['type'] ? $wpide_thanks_coupon['amount'] . '%' : wp_strip_all_tags( wc_price( $wpide_thanks_coupon['amount'] ) );
$text = sprintf( 'Thank you! Here is %1$s off your next order with code %2$s, valid for %3$d days.', $offer, $code, $wpide_thanks_coupon['days'] );
if ( $plain_text ) {
echo esc_html( $text ) . "\n\n";
return;
}
printf( '<div style="margin:20px 0;padding:16px;border:2px dashed #7f54b3;text-align:center"><p style="margin:0 0 8px">%1$s</p><p style="margin:0;font-size:22px;font-weight:700;letter-spacing:2px">%2$s</p></div>', esc_html( sprintf( 'Thank you! Enjoy %1$s off your next order (valid %2$d days):', $offer, $wpide_thanks_coupon['days'] ) ), esc_html( $code ) );
}, 10, 4 );
Notes
The coupon only works for the customer's billing email, expires after the set number of days and is created once per order.
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.