0

I am trying to sort orders added manually by sku.

I've tried all these codes: Sort order items by SKU in Woocommerce admin order pages
Sorting order items via a hooked function in WooCommerce
Sorting order items by SKU in Woocommerce email notifications

Underneath code is working to sort by name.

add_filter('woocommerce_order_status_changed', 'sortOrderItemsSKU', 10, 2);
function sortOrderItemsSKU($items, $order) {
    uasort( $items,
        function( $a, $b ) {
            return strcmp( $a['name'], $b['name'] );
        }
    );
    return $items;
}

But when changing to _sku / sku both not working.

function( $a, $b ) {
    return strcmp( $a['_sku'], $b['_sku'] );
}

Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
David
  • 17
  • 4
  • Your code can't work as woocommerce_order_status_changed is not the right hook to be used… The right hook is woocommerce_order_get_items as in this answer: https://stackoverflow.com/a/50048721/3730754 – LoicTheAztec Jul 18 '20 at 22:06

1 Answers1

-1

I did find another solution. It returns the sorted array, but somehow the items in the order aren't being sorted:

add_action( 'woocommerce_order_status_changed', 'process_offline_order', 10, 4 );
function process_offline_order( $order_id, $items, $order, $types = 'line_item' ){
            
    $order = new WC_Order( $order_id ); 
    $items = $order->get_items(); 
    
    $item_skus = $sorted_items = array();

    foreach ( $items as $item_id => $item ) {
        
        $product = wc_get_product( $item['product_id'] );
        $product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
                    
        $product = $item->get_product(); 
        $item_skus[$product->get_sku()] = $item_id;
        
    }
    
    ksort($item_skus);

    foreach( $item_skus as $keyL => $valueL ){
        $sorted_items[$keyL] = $items[$keyL];
        $sorted_items[$valueL] = $items[$valueL];
    }

    return $item_skus;
}

So the problem is probably within this part:

foreach( $item_skus as $keyL => $valueL ){
    $sorted_items[$keyL] = $items[$keyL];
    $sorted_items[$valueL] = $items[$valueL];
}   
return $item_skus;

Any suggestions?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
David
  • 17
  • 4