Attach a PDF to the WooCommerce order email
In this tutorial, I’ll show you how to upload a PDF file for each product in WooCommerce and have that file automatically attached to the new order email sent to the customer.
Add a PDF upload field to the product editor
We’ll use add_meta_boxto add a file input in the product edit screen:
<?php
add_action( 'add_meta_boxes', 'addProductPdfUploadBox' );
function addProductPdfUploadBox() {
add_meta_box(
'productPdfMeta',
'Customer PDF File',
'renderProductPdfMetaBox',
'product',
'side'
);
}
function renderProductPdfMetaBox( $post ) {
wp_nonce_field( 'saveProductPdfMeta', 'productPdfMetaNonce' );
$pdfUrl = get_post_meta( $post->ID, '_productPdfUrl', true );
echo '<input type="file" name="productPdfFile" accept="application/pdf" />';
if ( $pdfUrl ) {
echo '<p><a href="' . esc_url( $pdfUrl ) . '" target="_blank">View current PDF</a></p>';
}
}
Save the uploaded PDF file when saving the product
The uploaded file is saved in the uploadsfolder and its URL is stored in post meta:
<?php
add_action( 'save_post', 'saveProductPdfMeta' );
function saveProductPdfMeta( $postId ) {
if ( ! isset( $_POST['productPdfMetaNonce'] ) ||
! wp_verify_nonce( $_POST['productPdfMetaNonce'], 'saveProductPdfMeta' ) ) {
return;
}
if ( isset( $_FILES['productPdfFile'] ) && $_FILES['productPdfFile']['error'] === UPLOAD_ERR_OK ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
$uploadedFile = wp_handle_upload( $_FILES['productPdfFile'], [ 'test_form' => false ] );
if ( isset( $uploadedFile['url'] ) ) {
update_post_meta( $postId, '_productPdfUrl', esc_url_raw( $uploadedFile['url'] ) );
}
}
}
Attach the PDF to the new order email
We use the woocommerce_email_attachmentsfilter to add the PDF file to the customer new order email:
<?php
add_filter( 'woocommerce_email_attachments', 'attachProductPdfsToEmail', 10, 4 );
function attachProductPdfsToEmail( $attachments, $emailId, $order, $email ) {
if ( $emailId !== 'customer_processing_order' ) {
return $attachments;
}
foreach ( $order->get_items() as $item ) {
$productId = $item->get_product_id();
$pdfUrl = get_post_meta( $productId, '_productPdfUrl', true );
if ( $pdfUrl ) {
$uploadDir = wp_upload_dir();
$filePath = $uploadDir['basedir'] . str_replace( $uploadDir['baseurl'], '', $pdfUrl );
if ( file_exists( $filePath ) ) {
$attachments[] = $filePath;
}
}
}
return $attachments;
}
What does this do?
- You can upload a PDF file per product from the admin.
- That PDF will be automatically attached to the customer’s new order email if the product is purchased.
- Files are stored in the
uploadsfolder and are not publicly indexed unless someone has the direct link.




