如何根据 WooCommerce 中的产品 ID 更改发件人电子邮件

How to change sender email based on product id in WooCommerce

我正在尝试更改与 WooCommerce 中两个产品相关的所有电子邮件的发件人电子邮件,但不更改所有其他产品。

我有下面的代码来更改发件人电子邮件,但我不确定如何让它仅适用于这两种产品(按产品 ID 或类别)。

function change_sender_email( $original_email_address ) {
    return 'admin@example.com';
} 
add_filter( 'wp_mail_from', 'change_sender_email' );

我能以某种方式使用过滤器“woocommerce_email_recipient_customer_completed_order”吗?

我知道如何使用它来有条件地更改电子邮件的收件人,但我无法使用它来更改发件人电子邮件。

您可以使用:woocommerce_email_from_address

// Change email sender address
function my_email_from_address( $from_email, $wc_email ) {
    // Get the WC_Order object instance
    $order = $wc_email->object;

    // Get items
    $items = $order->get_items();

    // Loop through
    foreach ( $items as $item ) {
        // Get product ID
        $product_id = $item->get_product_id();

        // Compare          
        if ( $product_id == 30 ) {
            $from_email = 'my.email1@whosebug.com';            
        } elseif ( $product_id == 32 ) {
            $from_email = 'my.email2@whosebug.com';
        }
    }

    return $from_email;
}
add_filter( 'woocommerce_email_from_address',  'my_email_from_address', 20, 2 );