【问题标题】:Add an email attachment to WooCommerce notifications based on product category根据产品类别向 WooCommerce 通知添加电子邮件附件
【发布时间】:2021-03-22 12:57:00
【问题描述】:

对于我的某些产品,我需要向我的客户发送额外的 pdf(不是发票)。

在这篇文章的帮助下:https://wordpress.org/support/topic/attach-pdf-to-confirmation-email-for-specific-product/

我可以在每封订单确认电子邮件中附加附件。 然后我尝试更改代码以按产品 sku 过滤。

在这篇文章中,我找到了一些关于可用变量的信息,并了解了 WP3 的一些变化: How to get WooCommerce order details

这是我的代码,不幸的是它不起作用并且不再向确认电子邮件附加任何内容:

add_filter( 'woocommerce_email_attachments', 'webroom_attach_to_wc_emails', 10, 3);
function webroom_attach_to_wc_emails ( $attachments , $email_id, $order ) {
// Avoiding errors and problems
if ( ! is_a( $order, 'WC_Order' ) || ! isset( $email_id ) ) {
   return $attachments;
}

$file_path = get_stylesheet_directory() . '/Lizenzen/TestAttachment.pdf'; 
$product_sku    = '1234';

if( $email_id === 'customer_processing_order' ){
        foreach ($order->get_items() as $item_key => $item ):
        $product        = $item->get_product();
        if ( $product_sku === $product->get_sku() ) {
            $attachments[] = $file_path;    
        }
    endforeach;
    }


return $attachments;
  }

如何更改它以检查产品类别而不是 SKU?

一个普遍的问题是:如何调试这个 php 代码?有没有办法显示例如email_id 等变量来检查代码是否得到正确的值?

【问题讨论】:

标签: php wordpress woocommerce email-attachments email-notifications


【解决方案1】:

以下代码基于添加附件

  • 产品类别
  • $email_id === 'customer_processing_order'

其他$email_ids,见How to target other WooCommerce order emails


还要确保文件路径正确!


所以你得到:

function filter_woocommerce_email_attachments( $attachments, $email_id, $order, $email_object = null ) {    
    // Avoiding errors and problems
    if ( ! is_a( $order, 'WC_Order' ) || ! isset( $email_id ) ) return $attachments;

    // File path
    $file_path = get_template_directory() . '/Lizenzen/TestAttachment.pdf';
    
    // Specific categories, several could be added, separated by a comma
    $specific_categories = array( 'Categorie-A', 'categorie-1' );
    
    // Email id equal to (view: https://stackoverflow.com/a/61459068/11987538)
    if ( $email_id === 'customer_processing_order' ) {
        // Loop through order items
        foreach( $order->get_items() as $item ) {
            // Product ID
            $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();

            // Has term (product category)
            if ( has_term( $specific_categories, 'product_cat', $product_id ) ) {
                // Push to array
                $attachments[] = $file_path;
            }
        }
    }
    
    return $attachments;
}
add_filter( 'woocommerce_email_attachments', 'filter_woocommerce_email_attachments', 10, 4 );

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2019-07-19
    • 2021-07-22
    • 2019-05-30
    • 2022-01-02
    相关资源
    最近更新 更多