Attach a Product's Manual to Its Order Email
Adds a field to each product for a file from the media library, such as a manual or warranty card, and attaches it to the customer's completed order email.
Opens WPIDE on
Code
add_action( 'woocommerce_product_options_general_product_data', function () {
global $product_object;
woocommerce_wp_text_input( array(
'id' => '_wpide_email_attachment',
'label' => 'Email attachment',
'type' => 'url',
'placeholder' => 'Media library file URL',
'description' => 'Attached to the order completed email.',
'desc_tip' => true,
'value' => $product_object instanceof WC_Product ? $product_object->get_meta( '_wpide_email_attachment' ) : '',
) );
} );
add_action( 'woocommerce_admin_process_product_object', function ( $product ) {
// phpcs:ignore WordPress.Security.NonceVerification -- WooCommerce verifies the product save nonce.
if ( isset( $_POST['_wpide_email_attachment'] ) ) {
$product->update_meta_data( '_wpide_email_attachment', esc_url_raw( wp_unslash( $_POST['_wpide_email_attachment'] ) ) );
}
} );
add_filter( 'woocommerce_email_attachments', function ( $attachments, $email_id, $order ) {
if ( 'customer_completed_order' !== $email_id || ! $order instanceof WC_Order ) {
return $attachments;
}
foreach ( $order->get_items() as $item ) {
$url = get_post_meta( $item->get_product_id(), '_wpide_email_attachment', true );
$id = $url ? attachment_url_to_postid( $url ) : 0;
$file = $id ? get_attached_file( $id ) : '';
if ( $file && file_exists( $file ) && ! in_array( $file, $attachments, true ) ) {
$attachments[] = $file;
}
}
return $attachments;
}, 10, 3 );
Notes
Paste the file's media library URL into the product's "Email attachment" field; only files from your own media library are attached.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.