6
votes

In woocommerce, I've got 2 products which has product instructions PDF.

If customer buys any of those 2 products, I want to send its PDF along with order confirmation email.

Right now I'm using this code to send PDF with order confirmation email -

add_filter( 'woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3); 

function attach_terms_conditions_pdf_to_email ( $attachments, $status , $order ) {

    $allowed_statuses = array( 'new_order', 'customer_invoice', 'customer_processing_order', 'customer_completed_order' );

    if( isset( $status ) && in_array ( $status, $allowed_statuses ) ) {
         $your_pdf_path = get_template_directory() . '/media/test1.pdf'; 
         $attachments[] = $your_pdf_path; 
    } 
return $attachments; 
}

But this sends PDF to all order email. I want to send PDF only when customer has bought one of those 2 products.

I think I need to add condition with product id or something.

1
You just checked for the type of email (status) and not if the product is within the order.Adrian

1 Answers

0
votes

You may retrieve order items with $order->get_items() All you need to do is loop over this array and check for corresponding product ids :

function attach_terms_conditions_pdf_to_email ( $attachments, $status , $order ) {

$allowed_statuses = array( 'new_order', 'customer_invoice', 'customer_processing_order', 'customer_completed_order' );

if( isset( $status ) && in_array ( $status, $allowed_statuses ) ) {

    $attachment_products = array(101, 102) // ids of products that will trigger email
    $send_email = false;
    $order_items = $order->get_items();

    foreach ($order_items as $item) { // loop through order items
        if(in_array($item['product_id'], $attachment_products)) { // compare each product id with listed products ids
            $send_email = true;
            break; // one match is found ; exit loop
        }
    }

    if($send_email) {
        $your_pdf_path = get_template_directory() . '/media/test1.pdf'; 
        $attachments[] = $your_pdf_path;
    }
} 
return $attachments; 
}