【问题标题】:Get the product name or id in Woocommerce order email notifications在 Woocommerce 订单电子邮件通知中获取产品名称或 ID
【发布时间】:2018-02-21 03:23:26
【问题描述】:

我尝试在 woocommerce 中获取订单的产品名称,现在我可以使用以下方式获取运输方式:

add_action( 'woocommerce_email_after_order_table', 'wdm_add_shipping_method_to_order_email', 10, 2 );
function wdm_add_shipping_method_to_order_email( $order, $is_admin_email ) {
    echo '<p><h4>Shipping:</h4> ' . $order->get_shipping_method() . '</p>';
}

我尝试使用:

$order->get_name() or $order->get_id() 

但它显示内部服务器错误。请帮忙。

如何在订单电子邮件通知中获取产品的名称或 ID?

【问题讨论】:

  • 试试$order-&gt;id();
  • @dipak_pusti 这是错误的……在 woocommerce 3+ 中,要获取您使用的订单 ID $order-&gt;get_id(); 和产品 ID $product-&gt;get_id();... 如您所见,此问题是询问产品 ID 或产品名称…

标签: php woocommerce product orders email-notifications


【解决方案1】:

由于一个订单可以包含许多商品,因此您可以在一个订单中包含多个产品名称。您需要首先获取订单商品并遍历每个商品以获取产品名称或 ID。

这可以使用以下代码来完成(这将替换您的实际代码):

add_action( 'woocommerce_email_after_order_table', 'custom_email_after_order_table', 10, 4 );
function custom_email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) {

    // Displaying the shipping method used
    echo '<p><h4>'.__('Shipping', 'woocommerce').':</h4> '.$order->get_shipping_method().'</p>';

    $product_names = array();

    // Loop thougth order items
    foreach( $order->get_items() as $item_id => $item ){
        $product = $item->get_product(); // Get an instance of the WC_Product object
        $product_id = $item->get_product_id(); // Get the product ID

        // Set each product name in an array
        $product_names[] = $item->get_name(); // Get the product NAME
    }
    // Displaying the product names
    echo '<p><strong>'.__('Product names', 'woocommerce').':</strong> <br>'.implode( ', ', $product_names ).'</p>';
}

代码进入活动子主题(或活动主题)的 function.php 文件中。

经过测试并且有效。

【讨论】:

  • 嗨 Loic,感谢您的回复,我想知道订单中是否只有一件商品,并且该商品的名称已经显示在电子邮件收据上,我只想获取名称已经显示在电子邮件中。我该怎么做?
  • 到目前为止,您提供的代码非常棒!!非常感谢!
  • @JoeyWang 如果只有一项,implode( ', ', $product_names ) 代码无论如何都会输出该唯一名称。即使只有一个项目,您仍然需要使用 foreach 循环,以使用 WC_Order_Item_ProductWC_Product methods 获取该项目属性
  • 是的,我已经接受了,我可以再问一个问题吗?我可以获取产品的 ID 吗?
  • @JoeyWang 你可以在foreach循环外使用变量$product_id,你会得到最后一个商品的产品ID(所以你只有一个商品,这不是问题)。
猜你喜欢
  • 2019-08-27
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2018-06-04
  • 1970-01-01
  • 2017-04-21
  • 2019-01-12
相关资源
最近更新 更多