Send email notifications to a defined email address depending if a product in order has a specific TAG [closed]

wordpress.stackexchange https://wordpress.stackexchange.com/questions/385609

Pergunta

I looking to send new order woocommerce email notification to two diferent emails depending if a product in the order has a specific TAG or not. So far what I came up with was the following:

//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 .= ', myemail@gmail.com'; 
    elseif (!$product_tag) 
        $recipient .= ', otheremail@gmail.com';
}

I have adapted the above from some related code search but the above doesn´t seem to work

thanks in advance for any help

Foi útil?

Solução

To check product has TAG or not you have to fetch product from order and search in them.

//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 .= ', myemail@gmail.com'; 
    } elseif ( !$product_tag ) {
        $recipient .= ', otheremail@gmail.com';
    }

    return $recipient;
}

One more thing you are extending a filter hook so you have to return a value.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange
scroll top