I have developed a custom code which sends e-mails to the customers based on the category of the product they buy. The problem with my site is one product is having many categories. The script is working correctly, other than that it sends many emails equal to the number of categories a product have. I want it to send only one e-mail per product.
Here is the code:
add_action("woocommerce_order_status_changed", "wcepp_notification_email");
function wcepp_notification_email( $order_id, $checkout = null ) {
global $woocommerce;
$order = new WC_Order( $order_id );
if($order->status === 'processing' ) {
function wcepp_get_custom_email_html( $order, $heading = false, $mailer, $cat_slug ) {
$template = 'emails/woo-custom-emails-per-product-'.$cat_slug.'.php';
return wc_get_template_html( $template, array(
'order' => $order,
'email_heading' => $heading,
'sent_to_admin' => true,
'plain_text' => false,
'email' => $mailer
)
);
}
$liquify_array = array('cutting-agent', 'dabjuice-liquify');
$terpene_array = array('terpene-blends', 'strain-specific', 'hybrid', 'indica', 'sativa', 'terpene-sample-kits', 'hybrid-sample-kit', 'indica-sample-kit', 'sativa-sample-kit');
$isolates_array = array('raw-terpene-isolates', 'alpha', 'beta');
// getting the order products
$items = $order->get_items();
// let's loop through each of the items
foreach ( $items as $item ) {
$categories = get_the_terms( $item['product_id'] , 'product_cat' );
foreach( $categories as $categorie ) {
$cat_slug = $categorie->slug;
if(in_array($cat_slug, $liquify_array)) {
$new_cat_slug = 'liquify';
} elseif(in_array($cat_slug, $terpene_array)) {
$new_cat_slug = 'terpenes';
} elseif(in_array($cat_slug, $isolates_array)) {
$new_cat_slug = 'isolates';
}
if(isset($new_cat_slug)) {
// Create a mailer
$mailer = $woocommerce->mailer();
//Prepare Email
$recipient = $order->billing_email;
if($new_cat_slug == 'liquify') {
$subject = 'Instructions for usage of your Liquify Product';
} elseif($new_cat_slug == 'terpenes') {
$subject = 'Instructions for usage of your Terpenes Product';
} elseif($new_cat_slug == 'isolates') {
$subject = 'Instructions for usage of your Raw Terpenes Isolates';
}
$content = wcepp_get_custom_email_html( $order, $subject, $mailer, $new_cat_slug );
$headers = "Content-Type: text/html\r\n";
//send the email through wordpress
$mailer->send( $recipient, $subject, $content, $headers );
}
}
}
}
}
Any help in this regard will be appraciated.