Randomize the order of Products in "Features Collection"

WunderSticker
Tourist
6 0 2

Hello,

 

I have a store where on the Main page the first section is some Hand Picked Collections and after that All Products are listed with "Featured Collection", I have attached a Screenshot.

 

I have added all Available Collections to this Featured collection and it also shows all Products, however unfortunately it always orders them Alphabetically order and I would love that this is radomized. So each time a user opens or reloads the page it shows a different order of the products. 

I am not able to find any setting to randomise this content.

I am using the Spotlight Theme if this is relevant to this question.

 

The Store in Question is:

https://wundersticker.com/

 

Screenshot 2024-02-11 at 6.34.34 PM.png

Reply 1 (1)

ThePrimeWeb
Shopify Partner
1148 298 224

Hey @WunderSticker,

 

I had to go and study up on a whole algorithmn for this 😵. I just learned about it too, so if you are interested, it's called the Fisher-Yates Shuffle Algorithm

 

 

Go to your theme's "Edit Code" Option, then in the search bar type "theme.liquid"
Above the tag "</body>" tag paste the following. Screenshot attached for reference.

<script>
document.addEventListener('DOMContentLoaded', function () {
    var ul = document.querySelector('.product-grid');
    var lis = Array.from(ul.getElementsByClassName('grid__item'));

    for (var i = lis.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        ul.insertBefore(lis[j], lis[i]);
    }
});
</script>

 

sometimes that may not work, if it doesn't just use this. 

 

<script>
var shuffled = false;
setInterval(function() {

    if(shuffled) {
        return;
    }
    
    try{
        var ul = document.querySelector('.product-grid');
        var lis = Array.from(ul.getElementsByClassName('grid__item'));
  
        for (var i = lis.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            ul.insertBefore(lis[j], lis[i]);
        }
        shuffled = true;
    } catch {
       console.log('failed') 
    }
    
}, 1000)
</script>

 

 

Screenshot for reference

ThePrimeWeb_0-1707674398548.png

 

Was I helpful?

Buy me a coffee

🙂

Need help with your store? contact@theprimeweb.com