根据订单中的产品是否有特定标签,向定义的电子邮件地址发送电子邮件通知

时间:2021-03-23 作者:RBLe

我希望向两封不同的电子邮件发送新订单woocommerce电子邮件通知,这取决于订单中的产品是否有特定的标签。到目前为止,我想到的是:

//Custom NEW ORDER Email address depending on Product Tag
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 custom field value (with the right $order_id)    
    $product_tag = has_term( \'apples\', \'product_tag\' );

    if ($product_tag) 
        $recipient .= \', [email protected]\'; 
    elseif (!$product_tag) 
        $recipient .= \', [email protected]\';
}
我从一些相关的代码搜索中改编了上述内容,但上述内容似乎不起作用

提前感谢您的帮助

1 个回复
最合适的回答,由SO网友:Gautam Golakiya 整理而成

要检查产品是否有标签,您必须从订单中提取产品并在其中搜索。

//Custom NEW ORDER Email address depending on Product Tag
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;

    $items = $order->get_items();
    $order_has_term = false;

    if( !empty( $items ) ){
        foreach ( $items as $item ) {
            $product_id = $item[\'product_id\'];
            $product_has_tag = has_term( \'apples\', \'product_tag\', $product_id );
            if( $product_has_tag ){
                $order_has_term = true;
                // if we found term in one of the product than we break the loop
                // otherwise it will be override
                break;
            }
        }
    }

    if ( $order_has_term ) {
        $recipient .= \', [email protected]\'; 
    } elseif ( !$product_tag ) {
        $recipient .= \', [email protected]\';
    }

    return $recipient;
}
还有一件事是扩展过滤器挂钩,因此必须返回一个值。