Retrieve a number of randomly-chosen products in Shopify
I need a solution for retrieving a number of randomly-chosen products on my homepage (or any pages). I read in here: Featuring a number of randomly-chosen products on your homepage. But I think It’s not good for me. I continue reading an article here: Featuring one randomly-chosen product on your homepage. I think it’s a good solution. Really this solution supports retrieving only a product, but I can get more if I change the variant for “limit”. Good…. But after that I found an issue with it.
Example: That collection has 10 products and I want to retrieve 5 products. All are OK if the index number is 1 or 2 or 3 or 4 or 5 but if the index number is greater than 5 We will miss some products.
I’m thinking… and after I have solved this issue. Sharing with everybody.
Get index number:
1 | {% capture index %}{{ 'now' | date: '%S' | times: collection.products.size | divided_by: 60 }}{% endcapture %} |
Count product missing
1 2 | {% assign number_product_miss = collection.products.size | minus: index %} {% assign number_product_miss = number_to_show | minus: number_product_miss %} |
Now we can show products
1 2 3 | {% for product in collection.products offset:index limit: number_to_show %} PRODUCT LIST CODE {% endfor %} |
If the current index doesn’t take up enough of the products. We need add below code:
1 2 3 4 5 | {% if number_product_miss > 0 %} {% for product in collection.products offset:0 limit: number_product_miss %} PRODUCT LIST CODE {% endfor %} {% endif %} |