返回

如何为 WooCommerce 可下载产品设置不同的电子邮件收件人?

php

为 WooCommerce 可下载产品设置不同的电子邮件收件人

问题

许多电子商务平台允许商家出售数字产品,例如 PDF 电子书。WooCommerce 为此提供了虚拟和可下载产品选项。但是,当商家希望向不同收件人(例如作者)发送订单电子邮件时,可能会遇到挑战。

解决方案

要解决这个问题,我们需要修改 WooCommerce 的默认代码。以下是修改后的代码:

add_filter( 'woocommerce_email_recipient_new_order', 'custom_email_recipient_new_order', 10, 2 );
function custom_email_recipient_new_order( $recipient, $order ) {
    // Not in backend when using $order (avoiding an error)
    if( ! is_a($order, 'WC_Order') ) return $recipient;

    // Define the email recipients / product Ids pairs
    $recipients_product_ids = array(
        '[email protected]'   => array(698),
        '[email protected]'   => array(694),
        '[email protected]' => array(690, 547),
    );

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        // Loop through defined product categories
        foreach ( $recipients_product_ids as $email => $product_ids ) {
            $product_id   = $item->get_product_id();
            $variation_id = $item->get_variation_id();
            if( array_intersect([$product_id, $variation_id], $product_ids) && strpos($recipient, $email) === false ) {
                $recipient .= ',' . $email;
            }
        }
        // Check if the product is downloadable
        if ( $item->get_product()->is_downloadable() ) {
            // Get the downloadable file URL
            $download_url = wc_get_order_item_meta( $item->get_id(), '_downloadable_file_url', true );
            // Get the downloadable file name
            $download_name = wc_get_order_item_meta( $item->get_id(), '_downloadable_file_name', true );
            // Add a link to the downloadable file in the email
            $recipient .= ',' . $email;
        }
    }
    return $recipient;
}

该代码检查产品是否可下载,如果是,则获取可下载文件 URL 和文件名,并将其作为链接添加到电子邮件中。这样,收件人不仅可以收到订单通知,还可以直接从电子邮件中下载产品。

结论

通过修改 WooCommerce 的默认代码,我们成功地为可下载产品设置了不同的电子邮件收件人。这使商家能够有效通知作者他们的产品销售情况,从而简化了数字产品销售流程。

常见问题解答

  1. 此代码是否适用于所有 WooCommerce 版本?
    此代码适用于 WooCommerce 3.0 及更高版本。

  2. 我可以将代码添加到我的主题函数文件中吗?
    是的,你可以将代码添加到你的主题函数文件中。但是,建议使用代码片段插件,这样在你更新主题时不会丢失代码。

  3. 我可以使用此代码为物理产品设置不同的电子邮件收件人吗?
    此代码专门用于可下载产品。要为物理产品设置不同的电子邮件收件人,你需要使用不同的方法。

  4. 我无法让此代码正常工作。该怎么办?
    确保你已正确添加代码,并且你的 WooCommerce 版本符合要求。如果仍然有问题,请向 WooCommerce 支持寻求帮助。

  5. 是否有其他方法可以为 WooCommerce 中的可下载产品设置不同的电子邮件收件人?
    是的,有其他方法,例如使用第三方插件或自定义编码解决方案。然而,上面的代码提供了一种简单有效的方法来实现此功能。