Ask SkyVerge

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 πŸ™‚

Published by Justin Stern

Justin is one of our co-founders, and is our resident overengineer. He likes to write developer tutorials and make black magic happen in our plugins. He thinks that writing code is a lot easier than writing words.

15 Comments

  1. I want products in shop to show Alphabetically.
    What can I do now?

    Please Help

    • Hi! Under WooCommerce > Settings > Products you can change the “Default Product Sorting” to “Default Setting” (custom + name). This will work alphabetically.

      You can change order manually from there if you have certain products you want to display first by going to products and clicking “Sort Products” at the top – you can then drag and drop products. You can also adjust the order manually by going to Product Data > Advanced on a product page and changing the “Menu Order”. Products with menu order "0" will be displayed first, then 1, 2, 3, etc. The default for all products is 0.

  2. Hey, landed here for a way to know how to change default sorting inside ‘my account’ page
    How to approach where I want to change how subscriptions appear on my account

    How can we sort them by their status instead of order_id.
    So, the active subscriptions should show on top of the table & cancelled should show at the bottom.

    Any pointers would be awesome.
    Thanks in advance

    • IIRC there’s a filter in the method that Subscriptions uses to pull the subscriptions for the my account page. Take a look at the template and work backwards from there to find the right filter πŸ™‚

  3. Hey! I would like my order items to be sorted by a products custom field (storelocation in this case). I can’t get it working though. How would you sort on custom fields?

  4. Hi Beka,

    Thanks for the quick response and pointing me in the right direction.
    I’m not that great of a codewriter, so I’ve been trying and trying but still can’t get it to work. My last version below. Am I missing something or is this just not the right approach?

    Thanks in advance…

    add_filter(‘woocommerce_order_get_items’ , ‘custom_woocommerce_order_get_items’);
    function custom_woocommerce_order_get_items( $args ) {
    $args[‘orderby’] = ‘meta_value’;
    $args[‘order’] = ‘ASC’;
    $args[‘meta_key’] = ‘_location’;

    return $args;
    }

  5. Hi Beka, I don’t see my reaction to your post here, so I assume it didn’t come through. I’ve been trying to do the sorting in many diferent ways, without success. Lack of skills I guess :-(. Could you help me a bit further please?

    I’m using a filter to alter woocommerce_order_get_items, in the way you’ve described. What could I be missing here?

    • Hey Nick, we moderate comments to go through once a week πŸ™‚ it’s there now. I’m afraid I misunderstood your original question, so I’ve gone back through and taken a look at the filter we’re using. This would actually have to be a fair bit of code, as only certain pieces of item meta are available in the order details, while things like custom fields, SKUs, etc are not pulled in. It would be a bit complicated to do this, as you’d have to rebuild the order details to include your new item meta, then change the sorting using this. Sorry I don’t have better news!

  6. Hello,

    We are trying to sell travel packages with woocommerce.
    The shoppers will pick individual items from our shop.
    I wish to have a function in cart that the shopper can drag and drop the items, and re-arrange the sequence of the products, how that is possible?

    • Hey Michael, a drag and drop interface will require a fair bit of custom code, so while it’s possible, we’d recommend working with a developer on this. We typically recommend Codeable for these sorts of changes.

  7. thanks Beka there comment is very helpful for everyone!!!

    • Thanks so much for the help! I want to take it one step further: first, sorting by a custom field “Manufacturer”; and, then by product Name. This is the code I have so far . . . After it sorts by manufacturer how do I make it sort by product name within manufacturer?

      // sort products by Manufacturer
      add_filter(‘woocommerce_get_catalog_ordering_args’, ‘am_woocommerce_catalog_orderby’);
      function am_woocommerce_catalog_orderby( $sort_args ) {
      $sort_args[‘orderby’] = ‘meta_value’;
      // Sort by meta_value because we’re using alphabetic sorting
      $sort_args[‘order’] = ‘asc’;
      $sort_args[‘meta_key’] = ‘Manufacturer’;
      return $sort_args;
      }

  8. Hi Beka,
    is it possible to organize this sort with Category grouping? E.g. listing from A to Z for Cat 1, then from A to Z for Cat 2 and so on.

    Thanks in advance

Hmm, looks like this article is quite old! Its content may be outdated, so comments are now closed.