questions

Count for complete quantity of all order items in WooCommerce

Rate this post

I have the problem that I need the complete number of shop items for a for loop.

I’ve already tried:

$total_quantity += $item->get_quantity()
$total_quantity = $order->get_item_count();
$items_count = count( $order->get_items() );

Unfortunately without success.

Here is my code:

foreach ($order->get_items() as $key => $item) {
        $total_quantity = $order->get_item_count(); <-- NOT WORKING
    for ( $i = 0; $i < $total_quantity; $i++ ) {
        $content .= '<button class="accordion">' . $item->get_name() . '</button>';
  }
}

The for loop in the foreach loop is supposed to cause PDF buttons to be generated. Depending on which PDF button you press, the index is transferred to JavaScript and checks which button has just been clicked.

With $ item-> get_quantity it almost worked. However, the index ($i) is reset to 0 for another product. However, it must continue. That means or if the product was put into the shopping cart 5 times and another product was only put into it once, then the button is first correctly displayed 5 times with the correct index but not for the second product.

If you have any questions about the code or need examples, please let me know and I’ll update this post.

 

✔️Solution:

For order items, use WC_Order_Item_Product get_quantity() method as follow in a FOR loop:

$content = ''; // Initializing

// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
    // Loop through item quantity
    for ( $i = 1; $i <= $item->get_quantity(); $i++ ) {
        $content .= '<button class="accordion">' . $item->get_name() . ' (' . $i . ')</button>';
    }
}

This should work now…


To count the complete global order items quantity you can use:

$total_quantity = 0; // Initializing

// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
    $total_quantity += $item->get_quantity();
}
// Output
echo '<p>Total items quantity: '.$total_quantity.'</p>';

Leave a Reply

Your email address will not be published.

Back to top button