Puddinq.com sharing knowledge

Add attachment to WooCommerce mail for certain products

Add attachment to WooCommerce mail for certain products

Lets say you want an attachment.pdf added to an completed order mail in WooCommerce if certain products are in the order. How do you add and attachment in that case?

With the following code you be able to select one of the mails send in the proces and add the attachment if one of the predefined products is in that order.

If you add the code to your functions.php of your theme and add the attachment.pdf in the same folder, then change the product numbers to your requirements and test.

// here we hook our function in
add_filter( 'woocommerce_email_attachments', 'attach_pdf_to_order_mail', 10, 3);

// our function we are hookig in 
function attach_pdf_to_order_mail( $attachments, $status , $order ) {
     
    // we only add the file on completed order mails
    // all options array('new_order', 'customer_processing_order', 'customer_completed_order', 'customer_invoice', 'customer_note', 'low_stock', 'no_stock', 'backorder', 'customer_new_account', 'customer_invoice_paid');
    $allowed_statuses = array('customer_completed_order' );
 
    if( isset( $status ) && in_array ( $status, $allowed_statuses ) ) {
 
        // the numbers are product ID s or variation ID s
        $attachment_products = array('1304','295','29','30','31','441','449'); // ids of products that will trigger email
        $send_email = false;
        // get all products in the order
        $order_items = $order->get_items();
 
        // loop through all items in the order 
        foreach ($order_items as $item) { // loop through order items
            // if the current ID is in the array of $attachment_products ID s
            if(in_array($item['product_id'], $attachment_products)) { // compare each product id with listed products ids
                $send_email = true;
                break; // one match is found ; exit loop
            }
        }
 
        // if a match was found the attachment.pdf will be added
        if($send_email) {
            $your_pdf_path = dirname(__FILE__) . '/attachment.pdf';
            $attachments[] = $your_pdf_path;
        }
    }
    
    //return the array with attachments 
    return $attachments;
 
}

https://puddinq.mobi/content/uploads/2017/04/variation_id.png

Variation ID

https://puddinq.mobi/content/uploads/2017/04/product_id.png

Product ID