Shopify - Order Products By Custom Field

- 1 answer

we have a simple Shopify store using the free "Meta Fields Editor" to add a simple custom field integer value to each of the products. Some products will have a meta value of 3, others 2 or 1. Many will have no meta value at all. We would like to be able to display the products in search results, by the meta field value entered for each product in descending order (weighted ordering). However, despite the ability to set meta values and display them in search results and collections pages, Shopify does not make it easy to Order or Sort products by a custom meta field. In the search results page I am able to call the custom meta value using {{item.metafields.important.important}} So far I have tried to order the products using this method

{% assign products = collection.products | sort: 
'item.metafields.important.important' %}
{% for product in products %}
   {{ product.title }}
{% endfor %}

But this results in null results. Any insight anyone can give me in how to display products in order of a custom field would be much appreciated!



After attempting to find a Liquid solution I was finally able to solve this problem using custom metafields and jQuery. In the Shopify collection template, I added a data attribute to be included with each product like so:

<div id="product_list">
<div data-imp="{{product.metafields.important.important}}" class="product_block" /> PRODUCT #1 </div>
<div data-imp="{{product.metafields.important.important}}" class="product_block" /> PRODUCT #2 </div>

Then I used a simple jQuery function to sort the nodes by data attribute in descending order

var $wrapper = $('#product_list');

        $wrapper.find('.product_block').sort(function (a, b) {
            return +b.dataset.imp - +a.dataset.imp;
        .appendTo( $wrapper );

Hope this helps somebody!