creative designer

Shopify gives plenty of ways to sort collection products but things get a little tricky when you need to sort by metafield value. Sure you can still sort the products in a collection manually, but where's the cool factor in that? Let's explore a sorting method that doesn't need JavaScript.

The Logic

The idea here is that we'll:

  1. Loop over the collection products, throwing all the metafields values into an array (along with the product index)
  2. order that array based on the metafield value.
  3. Loop over our new array, outputting the products in the new order.

The Code

Jump to the gist direct for the product metafield sorting code, or just copy and paste from the embedded version below. There's two versions of the code but they are the same - one just has comments.

How to add the metafield?

If you're looking at this article you should know how to add a metafield already. You could use ShopifyFD but for this simple example give some love to the built in product bulk editor. If you're logged into your Shopify account right now the following link should shortcut you to the bulk editor with the metafields ready to edit.

Caveat.

This is only going to work if the collection has 50 or less products. So if your collection is bigger than that you're going to run into some weirdness. Keep em small peoples! Also, I am making the bold assumption that you've gone through an added metafields to each of the products, and that all the values are unique. I guess the unique part is not so important but if you want to have full control over the order each one will need a value.

The cool thing is that this sorting logic can be applied to anything - not just products. If you wanted to sort the collections page (so the list of collections), or blog posts, or even pages - this can do it. Have fun.

 

Like to work with me?

Let's talk