Search code examples
phpwordpresswoocommerceproductorders

From WooCommerce order items, create array of product IDs and quantities


I am trying to send woocommerce order information to an external api. I am using the following function:

add_action( 'woocommerce_new_order', 'send_order_to_api', 10, 2 );
function send_order_to_api( $order_id, $order ){
// api code here
}

The API wants to receive my data in the following format:

$incoming_order = [
    'spot_id'   => 1,
    'phone'     => '+0000000000',
    'products'  => [
        [
            'product_id' => 1,
            'count'      => 9
        ],
    ],
];

I know I need to get my woocommerce product information like this for example:

$order->get_items();

and I know I need to turn it into a loop like this:

$order_items = $order->get_items();
    foreach( $order_items as $product ) {
}

But this is where I am stuck


Solution

  • Try the following, to get for each product its ID and the quantity in a correct formatted array:

    add_action( 'woocommerce_new_order', 'send_order_to_api', 10, 2 );
    function send_order_to_api( $order_id, $order ){
        $products = array(); // Initializing
    
        // Loop through order line items
        foreach( $order->get_items() as $item ) {
            $product = $item->get_product(); // Get the product object
    
            $products[] = array( 
                'product_id' => $product->get_id(), // product ID
                'count'      => $item->get_quantity(), // product quantity
            );
        }
    
        $incoming_order = [
            'spot_id'   => 1, // ?
            'phone'     => $order->get_billing_phone(), // The billing phone
            'products'  => $products, // Here we set the correct formatted products array
        ];
    
        // HERE, your API Code …
    }
    

    It should work.