Woocommerce仅针对2种产品在订单电子邮件中发送PDF附件


Woocommerce send PDF attachments in order email only for 2 products

在wooccommerce中,我有两个产品,它们都有产品说明PDF。

如果客户购买了这两种产品中的任何一种,我想将其PDF与订单确认电子邮件一起发送。

现在我用这个代码发送PDF与订单确认电子邮件-

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; 
}

但这会将PDF发送到所有订单电子邮件。我只想在客户购买了这两种产品中的一种时发送PDF。

我想我需要添加产品id之类的条件。

您可以使用$order->get_items()检索订单项目你所需要做的就是在这个数组上循环并检查相应的产品ID:

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; 
}