Upload files to an order to attach them to the WooCommerce Order Completed email.
Update 26 August 2022: Shane asked how to upload files so that they are not public. I suggested using the
wp-content/uploads/woocommerce_uploads directory as it is .htaccess protected. Over a few emails Shane dived into the WooCommerce source and found a solution with the
upload_dir filters – essentially if the upload is from a WooCommerce order then the files are uploaded to the protected
As this functionality is not needed by everyone I converted the code (version 0.3) to the a PHP class and used a true/false member variable to determine where to upload attachments. This update also included code to inform the admin when CMB2 is not active.
Update 4 January 2023: Gaja asked if the attachments could be shown in the customer’s View Order page in their account. It was an easy addition. Version 0.5 of the code includes this. See the screenshot near the end of the post.
Update 13 September 2023: Enabled HPOS support by changing get_post_meta() calls to $order->get_meta() versions.
CMB2 does not yet support HPOS but I reported it and they’ve developed a fix that should be in the next release.
I previously wrote about conditionally attaching files to WooCommerce order email to the Completed order email.
A client asked how to attach custom photos of a product to the Completed order email. This meant that the list of files to attach to the email could not be a static list as it was for the other plugin. I copied and tweaked the meta box code form the Tracking Info to WooCommerce order post to allow for a list of files to be uploaded and associated with each order. CMB2 has the ‘file_list’ field type that allows the upload of multiple files. It is primarily intended for galleries but is perfect for this.
The files are attached via the ‘woocommerce_email_attachments‘ filter and checking that the email is the ‘customer_completed_order‘ one. The list of attachments is in the post meta and includes the attachment ID and url. The
url is not useful here as the path to the file is needed so it can be attached. The get_attached_file() API call retrieves this.
Upload before sending email
For the shop manager, the most important thing is to note is that the files must be uploaded before the order is marked Complete.
View attachments in customer’s View Order page
Gaja asked if the attachments could be shown in the customer’s View Order page in their account. Someone asked the same question on a Facebook group. It wasn’t hard to add this. Version 0.5 of the code includes this new feature.
I added an ‘Attached documents‘ section below the address section.
The settings for the ‘file_list‘ field limits it to image uploads (‘query_args‘ parameter). This can be commented out or edited to allow for different file types.