← Return to Content Library

How to Loop through & Sort Metaobjects in Shopify (Code Included)

Here's how I've done it in the past

This is based on a section I set up when I used to work in-house for a brand. I initially created the IG Slider style section. Then when Metaobjects were released, I figured this would be the perfect use case to apply them.

  1. Create a variable that represents the array of metaobjects
  2. For this example, I am sorting the metaobjects by a number value called 'order'. That is why I created another variable adding the sort filter.
  3. Next create a For Loop that loops through each item in the array ex: {% for collection in sortedArray %} {% endfor %}
  4. Now you can access each value in the metaobject by referencing the name you gave it when you set it up. ex: {{ collection.collection_url.value }}
{% assign collectionArray = shop.metaobjects.collection_item.values %}
{% assign sortedArray = collectionArray | sort: 'order' %}

<div>
  <div class="ig-story-flex-ctr">
    {% for collection in sortedArray %}
    <a href="{{ collection.collection_url.value }}" class="story-link">
      <div class="story-img" style="background-image: url('{{ collection.collection_image.value | img_url: '500x500'}}')"></div>
      <p class="story-collection-title">{{ collection.collection_title.value }}</p>
    </a>
    {% endfor %}
  </div>
</div>

I hope this helps! I mainly use this blog as a way to reference things that I have learned. Thanks!

Click here to view code →