Reputation: 13
This is my first question here, and I need your help. I tried researching this topic, but did not manage to understand what exactly I am doing wrong, so please bear with me. I am using the following code: ` add_filter( 'woocommerce_email_recipient_new_order', 'add_recipient', 10, 2 ); function add_recipient( $recipient, $order ) { if ( ! is_a( $order, 'WC_Order' ) ) return $recipient;
// Additional email recipient
$additional_email1 = "email#[email protected]";
$additional_email2 = "email#[email protected]";
// The term slug
$term_slug1 = "d1";
$term_slug2 = "d2";
$has_term = false;
// Iterating through each order item
foreach ($order->get_items() as $item_id => $item_obj) {
$product_id = $item_obj->get_product_id();
$product_obj = wc_get_product($product_id);
$product_attributes = $product_obj->get_attributes();
foreach( $product_attributes as $taxonomy_key => $term_value ){
if( $taxonomy_key == "pa_d" && $term_value == $term_slug1 ){
$recipient .= ','. $additional_email1;
$has_term = true;
break; // stop searching
}
if( $taxonomy_key == "pa_d" && $term_value == $term_slug2 ){
$recipient .= ','. $additional_email2;
$has_term = true;
break; // stop searching
}
}
if( $has_term ) break; // stop the main loop
}
return $recipient;
} `
I am now trying to adapt this code to work with the parent product. Ideally, this code should work for both variable and non-varible products, such that if a product contains the term "d1", regardless of whether it is variable or not, the email should always go to email#1. Same for d2 and email#2.
However, the code is not outputting any errors. Should I use $product->get_id() instead? Or what am I doing wrong?
Upvotes: 0
Views: 143
Reputation: 11282
Try the below code. I revised your code. try the below code.
// Additional email recipient
$additional_email1 = "email#[email protected]";
$additional_email2 = "email#[email protected]";
// The term slug
$term_slug1 = "d1";
$term_slug2 = "d2";
$has_term = false; // Initializing
// Loop though order items
foreach ( $order->get_items() as $item ){
// Only for product variations
if( $item->get_variation_id() > 0 ){
$product = $item->get_product(); // The WC_Product Object
$product_id = $item->get_product_id(); // Product ID
// Loop through product attributes set in the variation
foreach( $product->get_attributes() as $taxonomy => $term_slug ){
// comparing attribute parameter value with current attribute value
if ( $term_slug === $term_slug1 ) {
$has_term = true;
$recipient .= ','. $additional_email1;
}
if ( $term_slug === $term_slug2 ) {
$has_term = true;
$recipient .= ','. $additional_email2;
}
}
}
if( $has_term ) break; // stop the main loop
}
return $recipient;
Upvotes: 0