0

I found the code below which is sending an e-mail once a specific coupon code has been used, however the order details are obviously not visible in the content since it's only the defined text:

add_action( 'woocommerce_applied_coupon', 'custom_email_on_applied_coupon', 10, 1 );
function custom_email_on_applied_coupon( $coupon_code ){
    if( $coupon_code == 'bob' ){

        $to = "jack.hoover@gmail.com"; // Recipient
        $subject = sprintf( __('Coupon "%s" has been applied'), $coupon_code );
        $content = sprintf( __('The coupon code "%s" has been applied by a customer'), $coupon_code );

        wp_mail( $to, $subject, $content );
    }
}

Is there any possibilty to send order details in the content (message) such as {customer_name}, {order_number} or {coupon_amount}? If not, how can a new order be sent to an additional recipient only if that specific coupon code is used. Thanks for any assistance.

I've added the email variables added in the question, however I guess the trigger to understand which order it is and the order details in it should be included to my knowledge in order to get it running.

1 Answers1

0

Yes, it is possible, you just need to change the hook when the code is executed. Currently, it is executed in cart, but you want to wait for the order to be created.

add_action( 'woocommerce_checkout_order_created', 'custom_email_on_applied_coupon_in_order' );
function custom_email_on_applied_coupon_in_order( $order ){
    $my_coupon = 'bob';
    $send_mail = false;
    // get all applied codes
    $coupon_codes = $order->get_coupon_codes();
    foreach( $coupon_codes as $code )
    {
        if( $code == $my_coupon ) $send_mail = true;
    }
    // also check if there is a billing email, when an order is manually created in backend, it might not be filled and the mail will fail
    if( $send_mail && $order->get_billing_email() != '' )
    {
        $to = $order->get_billing_email(); // Recipient
        $subject = sprintf( __('Coupon "%s" has been applied'), $my_coupon );
        $content = sprintf( __('Hello %1$s %2$s, The coupon code "%3$s" has been applied'), $order->get_billing_first_name(), $order->get_billing_last_name(), $my_coupon );
        // you'll find more order details in the $order object, look here how to get it:  https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/  
        wp_mail( $to, $subject, $content );
    }
}
Chrostip Schaejn
  • 2,347
  • 1
  • 6
  • 13
  • Great, thanks for sharing the solution, which worked perfectly fine, appreciate your time. There where two mistakes in the code (&&) and ($coupon_code should become $code) in order to display the code in the subject. – Digital Summiteer Mar 19 '23 at 13:50