Skip to content

Instantly share code, notes, and snippets.

@zakhardage
Last active April 13, 2020 02:27
Show Gist options
  • Save zakhardage/6082538 to your computer and use it in GitHub Desktop.
Save zakhardage/6082538 to your computer and use it in GitHub Desktop.
Simple randomized cross sell for Shopify using fisherYates shuffle.
{% assign curProduct = product.handle %}
{% assign count = 0 %}
<div id="related">
<script>
function fisherYates ( myArray ) {
var i = myArray.length,j,temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random()*(i+1));
temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
}
var products = new Array();
{% if collection and collection.all_products_count > 1 %}
{% for product in collection.products %}{% unless product.handle == curProduct %}products[{{ count }}] = "<a href='{{ product.url | within: collection}}'><span>{{ product.title | truncate:23 }}<br />{{ product.price | money }}</span><img src='{{ product.featured_image | product_img_url:'large' }}' alt='{{ product.title | escape }}' /></a>";{% assign count = count | plus:1 %}{% endunless %}{% endfor %}
{% else %}
{% for product in collections.all.products %}{% unless product.handle == curProduct %}products[{{ count }}] = "<a href='{{ product.url | within: collection}}'><span>{{ product.title | truncate:23 }}<br />{{ product.price | money }}</span><img src='{{ product.featured_image | product_img_url:'large' }}' alt='{{ product.title | escape }}' /></a>";{% assign count = count | plus:1 %}{% endunless %}{% endfor %}
{% endif %}
fisherYates(products);
for(var i=0;i<6;i++) {
document.write(products[i]);
}
</script>
</div>
@0x50616e6f
Copy link

Very usefull code but for some reason it don't show up, I create a snippet with the code and then include it in product.liquid, I'm new in shopify so maybe I did something wrong. Can u help me setting it up properly?

@zakhardage
Copy link
Author

Not today Satan

@0x50616e6f
Copy link

xddd

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