Search code examples
phpwordpresswoocommercecode-snippetswordpress-shortcode

Send Woocommerce registration confirmation email when administrator register a new Woocommerce client


I'm trying to create a snippet that send the woocommerce registration confirmation email to the new woocommerce clients that are registered by the administrator so they can see their password or reset it.

Here is the snippet i've made :

function custom_trigger_new_customer_email($user_id) {
    if (in_array('customer', wp_get_current_user()->roles)) {
        WC()->mailer()->get_emails()['WC_Email_Customer_New_Account']->trigger($user_id);
    }
}
add_action('user_register', 'custom_trigger_new_customer_email', 1, 1);

But it does not seam to send the mail. Have you any solution ?


Solution

  • I've fix my problem: the problem was the way i was getting the roles here is my working snippet

    function custom_trigger_new_customer_email($user_id) {
        if (in_array('customer', get_userdata($user_id)->roles)) {      
             $generated_password = wp_generate_password(); // Generate a random password
            
            // Set the generated password for the user
            wp_set_password($generated_password, $user_id);
            
            $mailer = WC()->mailer()->get_emails()['WC_Email_Customer_New_Account'];
            $mailer->trigger($user_id, $generated_password, true);
        }
    }
    add_action('user_register', 'custom_trigger_new_customer_email', 1, 2);