Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce: get total number of items in order

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? :-)

like image 574
Austen Osborne Avatar asked Dec 23 '22 21:12

Austen Osborne


1 Answers

Counting order items can be 2 different things:

  1. 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;

  2. 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();
like image 50
LoicTheAztec Avatar answered Jan 18 '23 12:01

LoicTheAztec