1

I am trying to put the ordered items in a array to pass the values further in woocommerce thank you page. I am currently getting all line item names, sku etc without comma or anything.

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

    $item_quantity = $item_data->get_quantity(); // Get the item quantity

    $sku = $product->get_sku();
    $item_total = $item_data->get_total(); // Get the item line total

    // Displaying this data (to check)
    echo 'NAME: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 );

}

Current Results

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
user2940097
  • 63
  • 1
  • 1
  • 6

1 Answers1

0

This can be done easily with the following:

add_action( 'woocommerce_thankyou', 'thankyou_custom_items_data', 20, 1 );
function thankyou_custom_items_data( $order_id ) {
    // Get an instance of the the WC_Order Object
    $order = wc_get_order( $order_id );

    $items_data = array();

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

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

        $items_data[$item_id] = array(
            'name'       => $product->get_name(),
            'sku'        => $product->get_sku(),
            'quantity'   => $item->get_quantity(),
            'item_total' => number_format( $item->get_total(), 2 )
        );
    }
    // Testing array raw output
    echo '<pre>'; print_r( $items_data ); echo '</pre>';
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.

You will get a raw output like:

Array (
    [776] => Array (
        [name] => Happy Ninja
        [sku] => HN2563
        [quantity] => 1
        [item_total] => 36.36
    )
    [777] => Array (
        [name] => Patient Ninja
        [sku] => PN2559
        [quantity] => 1
        [item_total] => 29.17
    )
)

Related: Get Order items and WC_Order_Item_Product in Woocommerce 3

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • i have a small question though, the array returns each time increment by 4 like 776,777 then it would be 780, 781etc, how can I print and pass the incremental array with each order. – user2940097 Mar 14 '18 at 09:57
  • @user2940097 I don't catch what you want to do. The keys 776 and 777 are related to the **order "item_id"** that you can find in database within tables `wp_woocommerce_order_items` and `wp_woocommerce_order_itemmeta`. For each order, there is different types of items like "line_item", "tax", "fee", "shipping"… so the "line_item" item_id value jump from one order to another. If you don't need that you can just replace `$items_data[$item_id] = array(` by `$items_data[] = array(` … – LoicTheAztec Mar 14 '18 at 10:25