Cartoon of Author

@zackeryfretty

Retrieving the Quantity Returned for an Order Line Item in WooCommerce.

🗓

Every once in a while with WooCommerce I come across something that I feel should be easy to do but it ends up being overly complicated. Most recently I was working with a project that required me to output the number of items that still existed on an order line item after a partial return was given--the 'Net Quantity' if you will.

Take this screenshot for example:

I was expecting just a simple method to grab this number but as far as I can tell that's not a thing? After poking around for a bit I ultimately came up with this snippet that will itterate through the returns & orders to come up with the quantity returned by matching up the Product IDs:

function zf_get_line_item_returned_quantity( $item, $order ) {

    $returned_quantity = 0;

    foreach ($order->get_refunds() as $refund) {
        foreach ($refund->get_items() as $refunded_item) {
            if ($refunded_item->get_product_id() == $item->get_product_id()) {
                $returned_quantity += $refunded_item->get_quantity();
            }
        }
    }

    return $returned_quantity;

}

I am using this while iterating through the items in an order, passing the current item and the order object to it.

In the example above it will give you the '-3'.

Once you have that you can do some simple math to get the gross, returned, and net quantity of the line item:

$gross_quantity  = $item->get_quantity(); // 5
$returned_quantity = zf_get_line_item_returned_quantity($item, $order); // -3
$net_quantity  = $initial_quantity + $returned_quantity; // 2

At the time of writing this is working great for me! Hopefully it'll save someone out there some time. 😊

———