php - 如果 woocommerce 订单包含特定产品类别的商品,则发送电子邮件

标签 php wordpress woocommerce custom-taxonomy email-notifications

我在使用下面的代码时遇到了一些问题,我希望在 woo commerce 上完成订单时发送一封电子邮件,问题是它必须属于某个类别,有人可以帮忙吗。

add_action( 'woocommerce_catmail', 'my_function' );

    function my_function($order_id) {
       $order = wc_get_order( $order_id );

       foreach($order->get_items() as $orderid) {
          if ($orderid['product_cat']== 630) {
             $_product = get_product($item['product_id']);
             $to_email = $order->billing_email;
             $headers = 'From: Your Name <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86ffe9f3f4c6e3ebe7efeaa8e5e9eb" rel="noreferrer noopener nofollow">[email protected]</a>>' . "\r\n";
             wp_mail($to_email, 'subject', 'message', $headers );
          }
        }
    }

最佳答案

当订单状态更改为“已完成”时,以下代码将向客户发送特定产品类别的自定义电子邮件:

// On order completed status
add_action('woocommerce_order_status_completed', 'send_a_custom_email', 20, 1 );
function send_a_custom_email( $order_id ) {
    $order = wc_get_order( $order_id ); // The WC_Order object

    foreach ( $order->get_items() as $item_id => $item ) {
        $product = $item->get_product(); // The WC_Product object

        // Get the parent product ID for product variations for product categories
        $the_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

        if (  has_term( array( 630 ), 'product_cat', $the_id ) ) {
            $to_email = $order->get_billing_email(); // To customer
            $subject = "Your subject goes here";
            $message = "Your message goes here";
            $headers = 'From: Shop Name <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a0bbbca393b6beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>>' . "\r\n"; // From admin email

            wp_mail( $to_email, $subject, $message, $headers ); // Send email
            break; // Stop the loop
        }
    }
}

代码位于事件子主题(或事件主题)的functions.php 文件中。经过测试并有效

关于php - 如果 woocommerce 订单包含特定产品类别的商品,则发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49813079/

相关文章:

php - PDO 准备语句插入 1 而不是字符串

php - 如何通过 jquery 按钮在后台运行 PHP 脚本

javascript - AngularJS组织简单的Ajax程序?

php - 禁用未登录用户的结帐页面

php - 从 WooCommerce 中的国家代码获取国家名称

ajax 修改文件中的 JavaScript 在主页中不起作用

mysql - 合并 2 个 SQL 查询。

javascript - 将表单搜索提交数据传递到重定向结果页面

html - 图像叠加上的垂直居中按钮

php - 如何从woocommerce中的链接产品中获取分组的产品ID