简体   繁体   中英

Send an email notification to customer when a specific coupon code is applied in WooCommerce

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.

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

            wp_mail( $to, $subject, $content );
        }
    }
}
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 1 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM