phpwordpresswoocommerceuser-rolesemail-notifications

Woocommerce email notifications additional recipients based on user role


In Woocommerce, I am trying to send the "new order" email to extra email addresses. The other email addresses depend on what the role of the user is.

Based on "Adding a custom email recipient depending on selected custom checkout field value" answer code, making changes to it, here is my code:

add_filter( 'woocommerce_email_recipient_new_order', 'new_order_conditional_email_recipient', 10, 2 );
function new_order_conditional_email_recipient( $recipient, $order ) {
    if ( ! is_a( $order, 'WC_Order' ) ) return $recipient; // (Optional)

    // Get the order ID (retro compatible)
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    // Get the customer ID
    $user_id = $order->get_user_id();

    // Get the user data
    $user_data = get_userdata( $user_id );

    // Adding an additional recipient for a custom user role
    if ( in_array( 'user_role1', $user_data->roles )  )
        $recipient .= ', email1@gmail.com';
    elseif ( in_array( 'user_role2', $user_data->roles )  )
        $recipient .= ', email2@gmail.com';

    return $recipient;
}

I just can't seem to find out how to get user information from the order.

This is what I tried right now, but when I try to place an other I get an "internal server error".

So I am basically trying to find out how to get fields from the user who placed the order.


Solution

  • For user roles based, try the following:

    add_filter( 'woocommerce_email_recipient_new_order', 'new_order_conditional_email_recipient', 10, 2 );
    function new_order_conditional_email_recipient( $recipient, $order ) {
        if ( ! is_a( $order, 'WC_Order' ) ) 
            return $recipient; 
    
        // Get an instance of the WP_User Object related to the order
        $user = $order->get_user();
    
        // Add additional recipient based on custom user roles
        if ( in_array( 'user_role1', $user->roles )  )
            $recipient .= ', email1@gmail.com';
        elseif ( in_array( 'user_role2', $user->roles )  )
            $recipient .= ', email2@gmail.com';
    
        return $recipient;
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works.