Add recipients based on user role to failed and cancelled WooCommerce emails

后端 未结 1 421
花落未央
花落未央 2021-01-07 11:43

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

1条回答
  •  囚心锁ツ
    2021-01-07 11:50

    The hook you are already using is a composite hook: woocommerce_email_recipient_{$this->id}, where {$this->id} is the WC_Email ID like new_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.

    0 讨论(0)
提交回复
热议问题