How to Attach files to Order Emails in WooCommerce?

Previously, we have learnt how to add content to order email. We can also add a unique first name to your email subject in WooCommerce. Furthermore, you will learn how to attach files to order emails. There are many file types like PDF, Image files like jpg & png, xlsx, txt, etc. 

Files are an essential part for many order emails. However, you cannot simply add it using WooCommerce dashboard. Instead, you need to code a little bit and make it work! So, write a few PHP lines as quoted below.

Image showing how to attach files to emails

PHP Snippet: Attach files to Order Emails in WooCommerce

Firstly, you should upload a file like PDF somewhere on your system. You can upload it through the Media > Add New Section of WordPress dashboard. Otherwise, you can also place it in your child theme. To place it there, you need to work with get_stylesheet_directory().

In this example, we have taken example.pdf as a sample pdf. It is placed under /wp-content/uploads/2020/09/example.pdf. In this snippet, wp_upload_dir() function is used to return the uploads folder “path”. You do not need an absolute URL otherwise it won’t work. 

You can attach these files to “new_order” and “customer_processing_order” emails. 

add_filter( 'woocommerce_email_attachments', 'phpsof_attach_pdf_to_emails', 10, 4 );
 
function phpsof_attach_pdf_to_emails( $attachments, $email_id, $order, $email ) {
    $email_ids = array( 'new_order', 'customer_processing_order' );
    if ( in_array ( $email_id, $email_ids ) ) {
        $upload_dir = wp_upload_dir();
        $attachments[] = $upload_dir['basedir'] . "/2020/09/example.pdf";
    }
    return $attachments;
}

Where do you add this snippet?

So, this is how you can attach files to order emails in WooCommerce. Also, it is easier to activate this function with this code. So, to apply this code, just add this PHP snippet at your child theme function.php file’s bottom. It should be placed before “?>”, if you have it there. Apart from this, CSS goes in your child theme style.css file. Make sure that you are editing these files in a right manner for best results.

Is this snippet still valid?

So, this is how you can learn about attach files to order emails in WooCommerce. I have applied this code on the Storefront theme and WordPress friendly hosting PHP 7.3. Let me know if everything works as expected when you code. Share it further if you find this snippet useful for you and it had saved your time. 

Also Read, How to Modify Cart items count in WooCommerce?

How to Show Product Upsells at Thank You Page in WooCommerce?

Important links – WooCommerce – https://woocommerce.com/