Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.