Ask SkyVerge: How Do I Sort WooCommerce Order Items Alphabetically? February 08 2014

This week’s “Ask SkyVerge” question comes from Adrian, who wants to know:

Can you sort the items in the order alphabetically?
Ex: if someone orders broccoli, cabbage, string cheese
Can your organize the items in the order alphabetically?

Well, depending on where you need the items to appear sorted, you sure can! First, the code, which can be dropped into your current theme’s functions.php if you like:

/*
 * 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! Let us know in the comments below if you adapt this code to do something creative for your own purposes :)

The post Ask SkyVerge: How Do I Sort WooCommerce Order Items Alphabetically? appeared first on SkyVerge.