Search code examples
phpwordpresswoocommerceorders

Get Specific Data Structure with WooCommerce Order items


For one order placed and that order is having 3 products I should need to get a data structure formatted like:

[items] => Array
(
    [0] => Array
    (
        [sku] => Product 1 sku
        [qty] => Product 1 qty
        [price] => Product 1 price
        [weight] =>
        [discount] =>
        [line_ref] =>
    )

    [1] => Array
    (
        [sku] => Product 2 sku
        [qty] => Product 2 qty
    )

    [2] => Array
    (
        [sku] => Product 3 sku
        [qty] => Product 3 qty
    )

)

Here is my code:

$order = new WC_Order( $order_id );
// Get the order ID
$order_id = $order->get_id();

// Get data from Items
foreach ( $order->get_items() as $item_key => $item_values ) {  

    $product_id = $item_values->get_product_id(); // the Product id
    $product = $item_values->get_product(); // the WC_Product object
    $item_data = $item_values->get_data();

     $item = array(array(
        'sku'       => $product->get_sku(),
        'qty'       => $item_data['quantity'],
        'price'     => $product->get_price(),
        'weight'    => '',
        'discount'  => '',
        'line_ref'  => ''
        ),
        array(
        'sku'       => $product->get_sku(),
        'qty'       => $item_data['quantity'],
        )
     );

}
print_r($item);

How can I achieve this?

I am getting the only data of very first product present in an Order. And if I do print_r($item); within foreach loop then it repeats the whole data depending on number of products in an Order.


Solution

  • Try the following

    // Get an instance of the order Object
    $order = wc_get_order( $order_id );
    
    // Get the order ID
    $order_id = $order->get_id();
    
    // Initialising
    $items_data = array(); 
    $count = 0;
    
    // Loop through Order items
    foreach ( $order->get_items() as $item_id => $item ) {  
        $product_id = $item->get_product_id(); // the Product id
        $product    = $item->get_product(); // the WC_Product object
        $item_data  = $item->get_data(); // The line item unprotected data (array)
    
        if( $count === 0 ) {
            $items_data[] = array(
                'sku'       => $product->get_sku(),
                'qty'       => $item->get_quantity(),
                'price'     => $product->get_price(),
                'weight'    => '',
                'discount'  => '',
                'line_ref'  => ''
            );
        } else {
            $items_data[] = array(
                'sku'       => $product->get_sku(),
                'qty'       => $item->get_quantity(),
            );
        }
        $count++;
    }
    $output = array('items' => $items_data );
    
    // Testing output
    print_r($output);
    

    It should better work as you like.