1

I am trying to send an email to the customer after he has used a specific promo code 'FREECLASS' while checking out.

What I do is send the customer a code 'FREECLASS' after signing up. I want the customer to get an additional custom message after he uses that code.

Based on Send an email notification when a specific coupon code is applied in WooCommerce answer code, this is what I have done up until now but it is not working.

add_action( 'woocommerce_applied_coupon', 'custom_email_on_applied_coupon', 10, 1 );
function custom_email_on_applied_coupon( $coupon_code ){
    if( $coupon_code == 'FREECLASS' ){
    
    
    // Get user billing email
    global $user_login;
    $user = get_user_by('login', $user_login );
    $email = $user->billing_email;
    
    
        $to = "$email"; // Recipient
        $subject = sprintf( __('Coupon "%s" has been applied'), $coupon_code );
        $content = sprintf( __('The coupon code "%s" has been applied'), $coupon_code );

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

This is my first WooCommerce project so some help would be really appreciated.

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
lukaxzy
  • 21
  • 2

1 Answers1

2

There is no need to use global variables, via $user_id you can get the WC_Customer instance Object and then the billing email address

  • wp_mail() - Sends an email, similar to PHP’s mail function

So you get:

function action_woocommerce_applied_coupon( $coupon_code ) {
    // NOT logged in, return
    if ( ! is_user_logged_in() ) return;
    
    // Compare
    if ( $coupon_code == 'freeclass' ) {
        // Get user ID
        $user_id = get_current_user_id();
        
        // Get the WC_Customer instance Object
        $customer = New WC_Customer( $user_id );
        
        // Billing email
        $email = $customer->get_billing_email();
        
        // NOT empty
        if ( ! empty ( $email ) ) {
            // Recipient
            $to = $email;
            $subject = sprintf( __('Coupon "%s" has been applied', 'woocommerce' ), $coupon_code );
            $content = sprintf( __('The coupon code "%s" has been applied by a customer', 'woocommerce' ), $coupon_code );
            $headers = array( 'Content-Type: text/html; charset=UTF-8' );

            wp_mail( $to, $subject, $content, $headers );
        }
    }
}
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 1 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50