Add Coupon Code to Order Details on Thank You Page

Enhance the post-purchase experience for your WooCommerce customers by providing them with a personalized coupon code on the thank you page. This simple snippet automatically generates a unique coupon code and displays it prominently in the order details section of the thank you page, encouraging customers to return for future purchases.

/**
* Snippet Name:  Add Coupon Code to Order Details Thank You Page
* Snippet Author:  wpsnippets.dev
*/

//adding coupon code on thank you page
function wps_add_coupon_code_to_order_details( $order_id ) {
    $order = wc_get_order( $order_id );
    $user_id = $order->get_user_id();

    // Generate a unique coupon code for the user
    $coupon_code = 'NEWUSER' . $user_id; // Example: Prefix with 'NEWUSER' and append user ID
    
    // Create a coupon with the generated code
    $coupon = array(
        'post_title' => $coupon_code,
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'shop_coupon'
    );

    $new_coupon_id = wp_insert_post( $coupon );

    // Set coupon properties
    update_post_meta( $new_coupon_id, 'discount_type', 'percent' ); // Discount type: Percentage
    update_post_meta( $new_coupon_id, 'coupon_amount', 10 ); // Coupon amount: 10% discount
    update_post_meta( $new_coupon_id, 'individual_use', 'yes' ); // Individual use only
    update_post_meta( $new_coupon_id, 'customer_email', get_userdata( $user_id )->user_email ); // Limit coupon to user's email
    
    // Display coupon code on thank you page
    echo '<p>Your coupon code for 10% off your next purchase: <strong>' . $coupon_code . '</strong></p>';
}
add_action( 'woocommerce_thankyou', 'wps_add_coupon_code_to_order_details', 10, 1 );

Code Explanation

  • This snippet hooks into the woocommerce_thankyou action to add a coupon code to the order details section of the thank you page.
  • It generates a unique coupon code by prefixing ‘NEWUSER’ and appending the user’s ID to create a personalized code.
  • The generated coupon is created with a 10% discount, limited to individual use, and associated with the customer’s email address.
  • The coupon code is then displayed prominently on the thank you page, inviting customers to use it for their next purchase.

Leave a Comment

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

Scroll to Top