Admin Dashboard, Thank You Page

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:

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.

100 WooCommerce Conversion Rate Optimisation Tips

This field is for validation purposes and should be left unchanged.

Let’s collaborate!

Need to outsource WordPress development?

Join forces with UnlimitedWP for an outsourced white label web development service you can truly rely on.

First Timer Here?

Sign up to receive 20% off on your first month with us.