/** * Dispatch the email(s) * * @since 1.2 * @param int $order_id order identifier */ public function trigger($order_id) { // nothingtodohere if (!$order_id || !$this->is_enabled()) { return; } // only dispatch the voucher recipient email once, unless we're being called from the Voucher Recipient email order action if (get_post_meta($order_id, '_wc_pdf_product_vouchers_voucher_recipient_email_sent', true) && !(isset($_POST['wc_order_action']) && 'send_email_wc_pdf_product_vouchers_voucher_recipient' == $_POST['wc_order_action'])) { return; } $order = wc_get_order($order_id); $this->find[] = '{billing_first_name}'; $this->replace[] = $order->billing_first_name; $this->find[] = '{billing_last_name}'; $this->replace[] = $order->billing_last_name; // foreach voucher item in this order, if it contains a recipient email, // add the voucher to those being sent to that recipient. // foreach voucher recipient, send an email with any and all vouchers $recipient_emails = array(); $order_items = $order->get_items(); if (count($order_items) > 0) { foreach ($order_items as $order_item_id => $item) { if ($item['product_id'] > 0 && isset($item['voucher_id']) && $item['voucher_id']) { $voucher = new WC_Voucher($item['voucher_id'], $order->id, $item, $order_item_id); if ($voucher->get_recipient_email() && $voucher->file_exists(wc_pdf_product_vouchers()->get_uploads_path())) { if (!isset($recipient_emails[$voucher->get_recipient_email()])) { $recipient_emails[$voucher->get_recipient_email()] = array('count' => 0, 'message' => '', 'recipient_name' => $voucher->get_recipient_name()); } $recipient_emails[$voucher->get_recipient_email()]['count']++; // message to the recipient? if ($voucher->get_message()) { if ('' === $recipient_emails[$voucher->get_recipient_email()]['message']) { $recipient_emails[$voucher->get_recipient_email()]['message'] = $voucher->get_message(); } elseif ($recipient_emails[$voucher->get_recipient_email()]['message'] != $voucher->get_message()) { // guard against the admitedly edge case of multiple vouchers with different messages // being sent to the same recipient, by just not displaying a message. Cause it would // probably look odd to have a bunch of different messages in the same email $recipient_emails[$voucher->get_recipient_email()]['message'] = null; } } } } } } foreach ($recipient_emails as $recipient_email => $data) { $this->object = array('order' => $order, 'recipient_email' => $recipient_email, 'voucher_count' => $data['count']); $this->message = $data['message']; $this->recipient_name = $data['recipient_name']; $this->recipient = $recipient_email; $this->send($this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments()); } // record the fact that the vouchers have been sent update_post_meta($order_id, '_wc_pdf_product_vouchers_voucher_recipient_email_sent', true); }