根据购买的产品替换 WooCommerce 新订单电子邮件收件人

问题描述 投票:0回答:1

我有这个功能,可以根据购买的产品向不同的电子邮件地址发送额外的电子邮件。它运行良好,但它仍然会向 Woo 中给出的默认地址发送一封新订单电子邮件。有没有办法防止这种情况,以便新订单邮件仅到达下面函数中给出的地址?

add_filter( 'woocommerce_email_recipient_new_order', 'custom_email_recipient_new_order', 10, 2 );
function custom_email_recipient_new_order( $recipient, $order ) {
    // Not in backend when using $order (avoiding an error)
    if( ! is_a($order, 'WC_Order') ) return $recipient;

    // Define the email recipients / product Ids pairs
    $recipients_product_ids = array(
        '[email protected]'   => array(23),
        '[email protected]'   => array(24),
        '[email protected]' => array(53, 57),
    );

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        // Loop through defined product categories
        foreach ( $recipients_product_ids as $email => $product_ids ) {
            $product_id   = $item->get_product_id();
            $variation_id = $item->get_variation_id();
            if( array_intersect([$product_id, $variation_id], $product_ids) && strpos($recipient, $email) === false ) {
                $recipient .= ',' . $email;
            }
        }
    }
    return $recipient;
}
php wordpress woocommerce product email-notifications
1个回答
0
投票

使用以下修订后的代码版本,避免在至少有匹配产品(自定义收件人)时向默认收件人发送电子邮件:

add_filter( 'woocommerce_email_recipient_new_order', 'custom_email_recipient_new_order', 10, 2 );
function custom_email_recipient_new_order( $recipient, $order ) {
    // Not in backend when using $order (avoiding an error)
    if( ! is_a($order, 'WC_Order') ) return $recipient;

    // Define the email recipients / product Ids pairs
    $recipients_product_ids = array(
        '[email protected]'   => array(23),
        '[email protected]'   => array(24),
        '[email protected]' => array(53, 57),
    );
    $new_recipient = array(); // Initialize

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        $product_id   = $item->get_product_id();
        $variation_id = $item->get_variation_id();
        
        // Loop through defined product categories
        foreach ( $recipients_product_ids as $email => $product_ids ) {
            if( array_intersect([$product_id, $variation_id], $product_ids) && ! in_array($email, $new_recipient) ) {
                $new_recipient[] = $email;
            }
        }
    }

    if ( $new_recipient ) {
        return implode(',', $new_recipient);
    }
    return $recipient;
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.