Woman Viewing Laptop On Marble Table

How to sort WooCommerce order items alphabetically

2 min read
Beka Rice

To sort WooCommerce order items alphabetically, you can drop this code into your current theme’s functions.php:

 * Filters the $order->get_items() method results to order all line items by
 * product name
add_filter( 'woocommerce_order_get_items', function( $items, $order ) {

  uasort( $items, 
          function( $a, $b ) { 
            return strnatcmp( $a['name'], $b['name'] ); 

  return $items;

}, 10, 2 );

Which will give you something like the following, regardless of the original order the items were added to the cart:

Alphabetically Sorted Order Items

Alphabetically Sorted Order Items

So, How Does it Work?

This code takes advantage of the 'woocommerce_order_get_items' filter provided by the WooCommerce WC_Order::get_items() method to modify the returned set of order items from a given order. Note that we don’t actually alter anything about the order items, besides their, well, order.

Because the order items data structure is complex (it’s an array of associative arrays), to sort the items alphabetically while maintaining the original item keys, we use PHP’s uasort() function to order the items using a custom function we supply (lines 8-10 in the code above). This custom function simply delegates to another PHP core function: strnatcmp() which compares two strings using a “natural string comparison” algorithm (which if you’re interested you read all the really technical information about here). Bottom line is that it helps to sort strings in a very sensible way.

Taking it Further

Note that using this sample code as a starting point, items can be sorted any way you desire. Just return the correct value from that custom sorting function (lines 8-10): -1 if $a should appear before $b, 0 if $a and $b are the same, or 1 if $a should appear after $b.

As an example, to sort in reverse alphabetical order, replace line 9 with: return strnatcmp( $b['name'], $a['name'] );

Using this technique you could sort the order items by any criteria you prefer: by item quantity, by line total, anything!