检索 Woocommerce 订单中第一行项目的成本

Retrieve the cost of first line item in Woocommerce Order

我试图使用以下代码检索 Woocommerce 3.X 订单中第一行项目的成本,但它仅在订单中有一个产品时有效,如果有多个产品,它将回显时选择最后一个产品成本,请指出错误之处。

    foreach ($order->get_items() as $item_id => $item_data) {

        // Get an instance of corresponding the WC_Product object
        $product = $item_data->get_product();
        $product_name = $product->get_name(); // Get the product name
        $product_price = $product->get_price();
        $item_quantity = $item_data->get_quantity(); // Get the item quantity
        $item_total = $item_data->get_total(); // Get the item line total

        // Displaying this data (to check)
    }

谢谢!

foreach() 语句为数组或对象集合中的每个元素重复一组嵌入语句。


在每次迭代中,它将访问每个项目,因此在循环结束时,您将获得最后一个项目的成本。

为了return第一项的成本,在foreach()结束前添加break;

foreach ($order->get_items() as $item_id => $item_data) {

      .
      .

        break;
    }

这样 foreach() 将只重复第一项。

您可以使用 reset() php 函数只保留订单项数组中的第一个 $item,避免使用 foreach 循环:

$order_items = $order->get_items(); // Get the order "line" items
$item = reset($order_items); // Keep the 1st item

// Get an instance of the WC_Product object
$product = $item->get_product();
$product_name = $product->get_name(); // Get the product name
$product_price = $product->get_price(); // Get the product active price
$item_quantity = $item->get_quantity(); // Get the item quantity
$item_total = $item->get_total(); // Get the item line total

// Displaying the cost of the first item
echo $item_total;

已测试并有效