How can I sort metaobjects by date on my storefront?

How can I sort metaobjects by date on my storefront?

khard
Shopify Partner
22 1 8

Hello, I have a metaobject for a list of events. I want to output them in date order. I can't find how to sort them by date. Default output is by object create date, which does not work.

 

Simplified code example. All help appreciated. 

{% assign event = shop.metaobjects.events.values | sort: 'event.date' %}

{% for event in events %}
{{ event.title }}
{{ event.date }}
{{ event.location }}
{% endfor %}

 

Thank you! 

Replies 7 (7)

BSS-Commerce
Shopify Partner
3478 465 560

Hi @khard 
Can you kindly share your store link (with the password, if any) with us? We will check it and suggest you a solution if possible.

 

If our suggestions are useful, please let us know by giving it a like, marking it as a solution, or donating here .


Product Labels by BSS | B2B Solution & Custom Pricing


Need help from our expert? Kindly share your request with us via community@bsscommerce.com


BSS Commerce - Full-service eCommerce Agency
khard
Shopify Partner
22 1 8
The code is not live on the site as it is in development.

nadinethery
Shopify Partner
19 1 6

Not sure if this helps, but I came across a similar problem trying to sort metaobjects in a particular order different from alphabetical.

 

I found out that the "sort" filter always casts to string in order to compare for sorting. Maybe you can cast your dates into string (like timestamp or smth) and try to apply the filter to that directly. 

 

This was my case:

 

    {% assign sort_raw = shop.metaobjects.flavor_profile_body.values %}
    {% assign scale_options = sort_raw | sort: 'appearance_order' %}

 

Where `appearance_order` was a property of the metaobject, in `single_text` format with a number. 

nadinethery
Shopify Partner
19 1 6

BTW, I also find out that you need to first assign your original array to a variable. If you perform the filter directly, it doesn't work. 

13MV
Shopify Partner
1 0 0

+1 Would love to hear what the answer to this is as well. I looked everywhere for a way to do this - I'm sure I'm missing something simple, but I'm genuinely stumped.

Ryan_Mc
Explorer
46 0 17

Anyone figure out a way? 

Maksis
Shopify Partner
2 0 0

There is no native way of sorting a metaobject by created_at/updated_at field, as it is not even existent for liquid.
BUT, if you already have a date field in an event object, there is a workaround using that.
Just output whatever events you have, without sorting, and assuming you have something like event-card, add to its container a css style "order" with a date as a value. Format the date to start with the year and end with the smallest unit, i.e. 30 May 2025 09:00 -> 2505300900. The css style then would be (for this specific event) order: 2505300900. The outer container, holding all event-cards should have display: flex.