skip to Main Content

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


  1. 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();
    
    Login or Signup to reply.
  2. Use this to get total items in a order –

    $order = wc_get_order( $order_id );
    echo $order->get_item_count(); // Will display the total numbers
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search