Get quantity of refunded items in order for each item and calculate the difference between qty and refund qty


I have a custom code which displays order items in Woocommerce orders list in admin. Code displays products and its quantities as it follows on the screen bellow.

enter image description here

enter image description here

Problem is that when I partially refund the product for example product with quantity 1 is refunded to 0, it still shows the product in the list. What do I need to do is to change quantity based on the qty & refund qty. Example: if product Weider which is 300x in the order will be partially refunded 4 times as you could see the screen bellow, I want to display 296 instead of 300. If it reachs 0 (refund all), it will be gone from the list.

enter image description here

I tried this but in test field I always get -1 even if the refund quantity is more than only 1.

Code bellow:

add_action('manage_shop_order_posts_custom_column', 'orders_list_preview_items', 20, 2 );
function orders_list_preview_items($column, $post_id) {
    global $the_order, $post;
    if ('order_status' === $column) {
        // Start list
        echo '<ul class="orders-list-items-preview">';
        // Loop through order items
        //if ($refunds){ 
        foreach($the_order->get_items() as $item) {
    //$qtyfin = 0;
    foreach ( $the_order->get_refunds() as $refund ) {
    foreach ( $refund->get_items() as $refunded_item ) {
    //if ( absint( $refunded_item->get_meta( '_refunded_item_id' ) ) === $refunded_item ) {
          $qtyfin = $refunded_item->get_quantity();
            $product = $item->get_product();
            $img     = wp_get_attachment_url($product->get_image_id());
            $name    = $item->get_name();
            $qty     = $item->get_quantity();
            $stock = $product->get_stock_quantity();
            $quantityfinal = $qty;

            if ($stock <= 0){
                $sklad = "Nie je skladom";
            } else {
                $sklad =  '<x style="color:green">Skladom: </x> <x class="valuestock">'.$stock.'ks</x>';
            echo "<li>
                <img src=\"$img\" />
                <label>$quantityfinal</label> $name
                <label class='stock'>$sklad test: $qtyfin</label>
        // End list
        echo '</ul>';

Thank you in advance for your help!


This should work:

// Loop through order items
//if ($refunds){ 
foreach($the_order->get_items() as $item_key => $item) {
    $qtyfin = $the_order->get_qty_refunded_for_item( $item_key );

Answered By – Chrostip Schaejn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published