Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stevenhoney/e86bfe9ab7c60df14e555717478879e4 to your computer and use it in GitHub Desktop.
Save stevenhoney/e86bfe9ab7c60df14e555717478879e4 to your computer and use it in GitHub Desktop.
<?php
/**
* Modified from https://www.skyverge.com/blog/add-woocommerce-email-recipients-conditionally/
*
* Add another email recipient for admin New Order emails if a product from a specific category or with a specific tag is ordered
*
* @param string $recipient a comma-separated string of email recipients (will turn into an array after this filter!)
* @param \WC_Order $order the order object for which the email is sent
* @return string $recipient the updated list of email recipients
*/
function sv_conditional_email_recipient( $recipient, $order ) {
// Bail on WC settings pages since the order object isn't yet set yet
// Not sure why this is even a thing, but shikata ga nai
$page = $_GET['page'] = isset( $_GET['page'] ) ? $_GET['page'] : '';
if ( 'wc-settings' === $page ) {
return $recipient;
}
// just in case
if ( ! $order instanceof WC_Order ) {
return $recipient;
}
$items = $order->get_items();
// check if product from category or with tag is in order
foreach ( $items as $item ) {
$product = $order->get_product_from_item( $item );
$args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'names');
$product_cats = wp_get_post_terms( $product->get_id, 'product_cat', $args ); // could swap product_cat for product_tag
// add our extra recipient if there's a product from the category with slug "dieta" - commas needed!
// we can bail if we've found one, no need to add the recipient more than once
if ( $product && in_array( "dieta", $product_cats ) ) {
$recipient .= ', [email protected]';
return $recipient;
}
}
return $recipient;
}
add_filter( 'woocommerce_email_recipient_new_order', 'sv_conditional_email_recipient', 10, 2 );
@shakil6677
Copy link

hello Steve,
Where I can put this codes?
and where i can call the function?
Thanks.

@roundboxstudio
Copy link

I know this answer is late, but might help someone else. This code is placed in the functions.php file of your wordpress theme.

@ThornedRose
Copy link

This, unfortunately, did not work for me (Wordpress 4.9.5 and WC 3.3.5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment