I want to be able to change who receives the Woocommerce email notifications based on what role the user is when ordering.
For example, If the user is logged in as
The hook you are already using is a composite hook: woocommerce_email_recipient_{$this->id}, where
{$this->id}
is theWC_Email
ID likenew_order
. So you can set any email ID instead to make it work for the desired email notification.
Below You have the 3 hooks for "New Order", "Cancelled Order" and "Failed Order" that you can use for the same hooked function.
In your function, I have removed some unnecessary code and completed the code to get the customer data (the user roles) related to the order:
add_filter( 'woocommerce_email_recipient_new_order', 'user_role_conditional_email_recipient', 10, 2 );
add_filter( 'woocommerce_email_recipient_cancelled_order', 'user_role_conditional_email_recipient', 10, 2 );
add_filter( 'woocommerce_email_recipient_failed_order', 'user_role_conditional_email_recipient', 10, 2 );
function user_role_conditional_email_recipient( $recipient, $order ) {
if ( ! is_a( $order, 'WC_Order' ) ) return $recipient;
// 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( 'wholesale_customer', $user_data->roles ) )
$recipient .= ', shaun@example.com';
return $recipient;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works.