Send an email notification incl. order details when a specific coupon code is applied in WooCommerce

98 views Asked by At

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 = "[email protected]"; // 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

There are 1 answers

1
Chrostip Schaejn On

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 );
    }
}