Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attach files to WooCommerce order email - Upload files to an order to attach them to the WooCommerce Order Completed email.
<?php
/*
Plugin Name: Attach files to WooCommerce order email
Plugin URI: https://www.damiencarbery.com/2021/05/attach-files-to-woocommerce-order-email/
Description: Upload files to an order to attach them to the WooCommerce Order Completed email.
Author: Damien Carbery
Author URI: https://www.damiencarbery.com
Version: 0.1
*/
// Add the metabox to allow for manual entering (or editing) of tracking information.
add_action( 'cmb2_admin_init', 'dcwd_order_files' );
function dcwd_order_files() {
$cmb = new_cmb2_box( array(
'id' => 'order_attachments',
'title' => 'Order Attachments',
'object_types' => array( 'shop_order', ), // Limit to Order post type
'context' => 'side',
'priority' => 'high',
'show_names' => true, // Show field names on the left
) );
$cmb->add_field( array(
'desc' => 'Upload the files that will be attached to the "Completed order" email.<br/><br/>The files must be uploaded <strong>before</strong> marking the order Complete.',
'id' => 'order_file_list',
'type' => 'file_list',
'preview_size' => array( 100, 100 ), // Default: array( 50, 50 )
'query_args' => array( 'type' => 'image' ), // Set to only allow image attachments. This can be disabled or edited.
) );
}
add_filter( 'woocommerce_email_attachments', 'dcwd_conditionally_attach_order_files_to_order_email', 10, 4 );
function dcwd_conditionally_attach_order_files_to_order_email( $attachments, $email_id, $object, $email_obj ) {
// Only attach files to Completed Order email, otherwise return early.
if ( 'customer_completed_order' != $email_id ) {
return $attachments;
}
$files = get_post_meta( $object->get_id(), 'order_file_list', true );
foreach ( (array) $files as $attachment_id => $attachment_url ) {
$attachments[] = get_attached_file( $attachment_id );
}
return $attachments;
}
/*
// Test the code - list the paths to the attachments.
add_action( 'woocommerce_email_order_details', 'dcwd_testing_order_attachments_code', 10, 4 );
function dcwd_testing_order_attachments_code( $order, $sent_to_admin, $plain_text, $email ) {
$files = get_post_meta( $order->get_id(), 'order_file_list', true );
echo '<pre>', var_export( $files, true ), '</pre>';
foreach ( (array) $files as $attachment_id => $attachment_url ) {
echo '<p>', get_attached_file( $attachment_id ), '</p>';
}
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment