代码之家  ›  专栏  ›  技术社区  ›  Calvin Seng

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

  •  1
  • Calvin Seng  · 技术社区  · 8 年前

    我试图检索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)
        }
    

    谢谢

    2 回复  |  直到 8 年前
        1
  •  1
  •   LoicTheAztec    8 年前

    您可以使用 reset() php函数只保留订单项数组中的第一个$项,避免使用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;
    

    测试和工作

        2
  •  0
  •   Rania Ts    8 年前

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


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

    为了返回第一个项目的成本,请在foreach()末尾之前添加 break; .

    foreach ($order->get_items() as $item_id => $item_data) {
    
          .
          .
    
            break;
        }
    

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