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

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

SK_TG
Shopify Partner
21 0 8

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. 

Replies 3 (3)
SK_TG
Shopify Partner
21 0 8

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. 

Bundler-Manuel
Excursionist
137 7 19

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!

Emmanuel
Please let me know if it works by marking it as a solution!
Bundler - Product Bundles app, a great bundle app for Shopify, with glowing user testimonials and a free plan.
SK_TG
Shopify Partner
21 0 8

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