Woocommerce Order Status Email Filter

58 Views Asked by At

I managed to get an email filter based on product author to work (sort of) It does actually work if I manually go to an order and change its order status to 'Processing' for example. This triggers the email and it sends to the relevant product author.

However when an actual order is made, even though the status of that order is set to 'Processing' the email is not being sent when I use the below filters.

If the filter is removed it sends the email to all recipients as expected, so what is causing the email alert not to trigger on actual orders when I add my filter?

I also tried swapping 'woocommerce_email_recipient_new_order' with 'woocommerce_email_recipient_processing_order' but still no luck.

I thought it might be something to do with the script load order so I tried using 5, 2 instead of 10, 2 to load the filter script first but again no emails get sent using the filter.

I'm really stuck with this, any help would be appreciated.

add_filter('woocommerce_email_recipient_new_order', 'custom_modify_order_recipients', 10, 2);
add_filter('woocommerce_email_recipient_cancelled_order', 'custom_modify_order_recipients', 10, 2);
add_filter('woocommerce_email_recipient_failed_order', 'custom_modify_order_recipients', 10, 2);

function custom_modify_order_recipients($recipient, $order) {
    // Check if the order object is valid
    if (is_a($order, 'WC_Order')) {
        $items = $order->get_items();

        // Get the product IDs from the order
        $items = $order->get_items();
        $product_ids = wp_list_pluck($items, 'product_id');

        // Set an array of email addresses indexed by product authors
        $author_email_map = array(
            '14' => '[email protected]',
            '488' => '[email protected]',
            '489' => '[email protected]',
        );

        // Initialize an array for email recipients
        $email_recipients = array();

        // Loop through product IDs and add recipients based on the author_email_map
        foreach ($product_ids as $product_id) {
            $product_author_id = get_post_field('post_author', $product_id);
            if (isset($author_email_map[$product_author_id])) {
                $email_recipients[] = $author_email_map[$product_author_id];
            }
        }

        // If there are recipients in the array, return the comma-separated list
        if (!empty($email_recipients)) {
            return implode(', ', $email_recipients);
        } else {
            // Return an empty string to prevent sending the email
            return '';
        }
    }

    return $recipient; // Otherwise return the original recipient
}
0

There are 0 best solutions below