I’m developing a plugin that sends WooCommerce order data to a REST API, using a Basic Authentication Header.
As for the WooCommerce order lines, the API documentation tells me to add every order line as an object to the ‘lines’ array. I’m struggling to set that up.
See the following code for more clarification:
$items = array();
foreach ( $order->get_items() as $item_id => $item_data ) {
$product = $item_data->get_product();
$product_name = $product->get_name();
$item_quantity = $item_data->get_quantity();
$item_total = $item_data->get_total();
$items[] = array(
'unit' => $product_name,
'quantity' => $item_quantity,
'price' => $item_total
);
}
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 20,
'headers' => array(
'username' => '***',
'password' => '***',
'company' => '***'
),
'body' => array(
'employee' => 1,
'debtor' => 1,
'deliveryMethod' => 1,
'deliveryAddress' => array(
'address' => $order->get_billing_address_1(),
'postcode' => $order->get_billing_postcode(),
'city' => $order->get_billing_city(),
'country' => 'NL'
),
'lines' => array(
'unit' => $items['unit'],
'quantity' => $items['quantity'],
'price' => $items['price']
)
)
) );
The WordPress debug log tells me it can’t find the index of ‘unit’, ‘quantity’ and ‘price’.
2
Answers
So your array variable would look similar to the following (basing from your example code):
The empty strings would just have your data.
You’re adding an array to an array, so if you wanted to parse through the
$items
array you could useforeach
:That output should be similar to:
But it would loop over each array in
$items
, so in my case using the above code it wouldprint_r()
three times.Another way to visualize it is:
Each array is indexed (unless you define a key) so
[0]
would be the first array in the$items
array, then you’re referencing the['unit']
key.Here’s a link to something that could help you understand more: https://www.geeksforgeeks.org/multidimensional-arrays-in-php/
Hope this helps!
Your array apparently looks ok except few things that is different than the documents.
First use ‘line_items’ instead of ‘lines’.
Now, each order may have one or many products so you have to associate ‘line_items’ with products. And you’re trying to get attributes which are related to those product. You got error because you’ve not associated quantity and price with product_id according to the docs.
Unit is something different. Unit could be get from meta. I guess you’re referring unit of dimensions. To get meta you can use it like
Here I’ve used every sample data. You can assign your desire data your way.
Hope this help you and your API should work correctly now!