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.
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.
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.