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? :-)
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):
// Get an instance of the WC_Order Object
$order = wc_get_order( $order_id );
$total_quantity = $order->get_item_count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With