Search code examples
phparrayswordpresswoocommerceorders

Retrieve the cost of first line item in Woocommerce Order


I was trying to retrieve the cost of first line item in Woocommerce 3.X order with the following code but it only works when there is one product in the order, if there is more than one, it will pick the last product cost when echoed, kindly advise what went wrong.

    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)
    }

Thanks!


Solution

  • The foreach() statement repeats a group of embedded statements for each element in an array or an object collection.


    In each iteration it will access each item, therefore in the end of the loop you will have the cost of the last item.

    In order to return the cost of the first item, add before the end of the foreach() break;.

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

    In this way the foreach() will only repeat for the 1st item.