WooCommerce Create Coupon Code Automatically After Purchase

WooCommerce thank you page showing custom coupon code automatically generated


There are no pre-requisites in order for you to be able to implement this solution.

How To Implement This Solution?

Simply copy the pre-coded solution to your active theme’s functions.php or preferably the Code Snippets Plugin.

About this Solution

This snippet automatically creates a coupon code when an order is placed and lets the customer know to share said coupon code to give their friend money off. Specifically, this code creates a coupon code based on the customer’s name and the discount amount. For example, if I made an order, a discount code called ALEX20 would be automatically generated which gives users 20% off.

 * Snippet Name:    WooCommerce Create Referral Coupon Code Automatically After Purchase 
 * Snippet Author:  ecommercehints.com

add_action( 'woocommerce_thankyou', 'ecommercehints_create_referral_coupon_code_automatically_after_purchase' );
function ecommercehints_create_referral_coupon_code_automatically_after_purchase($order_id) {

    $order = wc_get_order( $order_id );

    $billing_first_name = $order->get_billing_first_name();
    $coupon = new WC_Coupon();
    $coupon->set_code( $billing_first_name . '20' ); // Coupon code
    $coupon->set_amount( 20 ); // Discount amount
    $coupon->set_discount_type( 'percent' );


    echo 'Refer a friend with coupon code: ' . $billing_first_name . '20 and they\'ll get 20% off their order';


Coupon dashboard with automatically generated coupon code

WooCommerce coupon dashboard showing automatically generated coupon code

Snippet Benefits

  • Implement your own referral scheme by creating a tailored coupon code based on the customer’s name.
WooCommerce Conversion Rate Optimisation (CRO) eBook
100 WooCommerce Conversion Rate Optimisation Tips

Leave a Reply

If you are going to write code in the comments, please wrap it between code tags.

Your email address will not be published. Required fields are marked *

Other Recent Guides

Subscribe To Emails

Get exclusive WooCommerce tips that I only share with email subscribers

Join hundreds of other subscribers