Skip to content

Instantly share code, notes, and snippets.

Last active October 8, 2023 15:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magician11/86f2e28d58f4accbd70f to your computer and use it in GitHub Desktop.
Save magician11/86f2e28d58f4accbd70f to your computer and use it in GitHub Desktop.
How to sort a collection in Shopify based on a custom metafield.
This code displays the dropdown for the options to sort from.
Adapted from
It will be inserted on every collections page. Probably in a snippet called something like collection-sorting.liquid
<div class="form-horizontal">
<label for="SortBy" class="uppercase">{{ 'collections.sorting.title' | t }}&nbsp;</label>
<select name="SortBy" id="SortBy">
<option value="upcoming-events">Upcoming events</option>
<option value="best-selling">{{ 'collections.sorting.best_selling' | t }}</option>
<option value="title-ascending">{{ '' | t }}</option>
<option value="title-descending">{{ '' | t }}</option>
Shopify.queryParams = {};
if ( {
for (var aKeyValue, i = 0, aCouples ='&'); i < aCouples.length; i++) {
aKeyValue = aCouples[i].split('=');
if (aKeyValue.length > 1) {
Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
$(function() {
.val('{{ collection.sort_by | default: 'upcoming-events' }}')
.bind('change', function() {
Shopify.queryParams.sort_by = jQuery(this).val();
console.log(Shopify.queryParams); = jQuery.param(Shopify.queryParams);
This code is the modification needed for each product rendered by liquid.
We need to tag each product with the custom metafield here.
You'll probably be editing a snippet like product-grid-item.liquid
<div data-date="{{ }}">
<!-- the rest of your product ... -->
Then in the collection.liquid template itself:
First make sure that all products appear on the one page by increasing
the paginate by amount. I've set it to 100 in my case.
Then we check what is being sorted on. If it's the custom metafield we
re-arrange the DOM elements using this code.
Adapted from
{% paginate collection.products by 100 %}
var searchQuery = /sort_by=(.+)/g.exec(;
if(searchQuery === null || searchQuery[1] === 'upcoming-events') {
var eventListContainer = $('.event-container');
var eventList = eventListContainer.children('div');
eventList.sort(function(a,b) {
var event1date = new Date(a.getAttribute('data-date'));
var event2date = new Date(b.getAttribute('data-date'));
if(event1date > event2date) {
return 1;
if(event1date < event2date) {
return -1;
return 0;
Copy link

Which div is this? Where do we define this var eventListContainer = $('.event-container');?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment