How to sort products in a collection by Published_at not Created_at date?

I want to sort products in my collection by published_at not created_at date. The default Shopify “Newest” sort, sorts it by created_at date.. which is problematic when you keep products drafted for a while, and then you publish them and it doesn’t show on the store as a new / latest product.
Its time consuming to order Manually or use New tags during publishing.

I’m using Be Yours theme by Roar theme.. not interested in using a plugin, but happy to do code modifications.

1 Like

Hey there pal @SK_TG you actually indeed don’t need an app to resolve this issue. Here’s a code that should help you sort the products by when they were published

{% if collection.sort_by == ‘created-descending’ or collection.sort_by == empty and collection.default_sort_by == ‘created-descending’ %}
{% assign collection_products = collection.products | sort: ‘published_at’ | reverse %}
{% elsif collection.sort_by == 'created-ascending ’ or collection.sort_by == empty and collection.default_sort_by == ‘created-ascending’ %}
{% assign collection_products = collection.products | sort: ‘published_at’ %}
{% else %}
{% assign collection_products = collection.products %}
{% endif %}

Copy and paste appropriately and I think this should solve it!

I’m a developer myself and can carry out the code changes. Issue is, there’s no documentation in Be Yours theme to do this.
I have tried a few ways and its not 100% correct.. cuz I’m overriding the default sorting code, but I need to replace it altogether rather than override.

Hello, thank you. I’ll definitely try it out!

Thanks for the code. Where should it be placed?