从 WooCommerce 3 中的电子邮件模板获取产品 ID

Get the Product ID from email templates in WooCommerce 3

在 Woocommerce 中,我试图了解如何在客户完成的订单电子邮件模板中获取已完成订单的 产品 ID 以将其存储为 PHP多变的。这样我就可以将它插入到外部数据库中。

我已经试过了$product->get_id();但是还是不行。

如何从电子邮件模板中获取 WooCommerce 3+ 中的产品 ID?

您需要遍历订单项...通常 WC_Order 对象是通过变量 $order 定义的,大多数情况下在电子邮件模板中随处定义。

因此获取产品 ID 的代码将是:

// Loop through order items
foreach( $order->get_items() as $item_id => $item ){

    // Get the product ID
    $product_id = $item->get_product_id(); 

    // Get an instance of the WC_Product object
    $product = $item->get_product(); 

    // Get product title (name)
    $product_name = $product->get_title(); // or $product->get_name();

    // Get product price
    $product_price = $product->get_price(); 
}

查看相关主题: