This seems so simple, but it was late and I might have been over-complicating things!
I’m currently using the woocommerce_thankyou
hook in the WP
functions file to compile some data and send it to a third party API. So far, so easy, using standard $order
and $order_meta values
. But I need to get the total number of items in an order, and I can’t see where to get it.
So if someone orders 2
green widgets and 3
blue widgets, I need to get 5
from somewhere.
Am I missing something obvious? 🙂
2
Answers
Counting order items can be 2 different things:
Total items count:
// Get an instance of the WC_Order Object
$order = wc_get_order( $order_id );
$items_count = count( $order->get_items() );
// Testing output
echo $items_count;
The total items quantity count:
// Get an instance of the WC_Order Object
$order = wc_get_order( $order_id );
$total_quantity = 0; // Initializing
// Loop through order items
foreach ( $order->get_items() as $item ) {
$total_quantity += $item->get_quantity();
}
// Testing output
echo $total_quantity;
Or you can use the WC_Order
get_item_count()
method that do the same (see its source code):Use this to get total items in a order –