Forked from monecchi/mr_wc_new_order_email_recipient.php
Created
March 6, 2023 04:43
-
-
Save KoolPal/23ee13bc851ac95a34a3f2e551d125e8 to your computer and use it in GitHub Desktop.
WooCommerce New Order Email to different recipient based on customer's city
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add another email recipient for admin New Order emails if a shippable product is ordered for a specific city | |
* | |
* @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 mr_wc_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(); | |
$billing_city = $order->get_billing_city(); | |
$billing_city = array(); | |
$customer_city = array('New York'); | |
// check if a shipped product is in the order | |
foreach ( $items as $item ) { | |
$_product = $order->get_product_from_item( $item ); | |
// add our extra recipient if there's a shipped product - commas needed! | |
// we can bail if we've found one, no need to add the recipient more than once | |
if ( $_product && $_product->needs_shipping() && in_array( $billing_city, $customer_city) ) { | |
$recipient .= ', newemail@example.com'; | |
return $recipient; | |
} | |
} | |
return $recipient; | |
} | |
add_filter( 'woocommerce_email_recipient_new_order', 'mr_wc_conditional_email_recipient', 10, 2 ); | |
// Ensures Mail header is properly set so emails are not sent to spam folder | |
add_filter( 'woocommerce_email_headers', 'add_bcc_to_wc_admin_new_order', 10, 3 ); | |
function add_bcc_to_wc_admin_new_order( $headers = '', $id = '', $wc_email = array() ) { | |
if ( $id == 'new_order' ) { | |
$headers .= "Bcc: newemail@example.com\r\n"; | |
} | |
return $headers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment