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:

ID, '_productPdfUrl', true );

    echo '';
    if ( $pdfUrl ) {
        echo '

View current PDF

'; } }

 

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:

 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:

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 uploads folder and are not publicly indexed unless someone has the direct link.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Back to Top
0
Would love your thoughts, please comment.x
()
x