I have the following code and i am trying to display a specific product by the value in the Array “products” . Is this possible ?
My goal is to have the opportunity to call a random product by its ID in a specific collection.
Thanks for your help !
{% assign collection = collections['TEST] %}
{% for product in collection.products %}
{% endfor %}
Hi @yungmuehle , see if you can make the below Liquid code work,
{% assign collection = collections['TEST'] %}
{% assign specific_product_id = 1234567890 %}
{% for product in collection.products %}
{% if product.id == specific_product_id %}
{{ product.title }}
{% break %}
{% endif %}
{% endfor %}
Hope it’s a good start for you.
1 Like
Awesome thank you ! But is there a logic behind numbers of the Product ID ? Because i am looking for a range to select them randomly
Okay let’s improve the code. Try this,
{% assign collection = collections['TEST'] %}
{% assign product_ids = '1234567890, 9876543210' | split: ', ' %}
{% assign random_index = 'now' | date: '%s' | modulo: product_ids.size %}
{% assign random_product_id = product_ids[random_index] %}
{% for product in collection.products %}
{% if product.id == random_product_id %}
{{ product.title }}
{% break %}
{% endif %}
{% endfor %}
- Replace ‘1234567890, 9876543210’ with the IDs of the products you want to include in the array. These should be the actual numeric IDs of the products.
- The random_index line generates a random number based on the current timestamp and uses it to pick an ID from the product_ids array.
- The for loop iterates through the products in the collection and displays the product that matches the randomly chosen ID.
i think .size is wrong because it returns the number of characters in a string or the number of items in an array. Not the value
I am making progress and now it looks like the value for the “random_id” item isnt recognized in the if-loop. I think its because of the format because when i compare it to the actual product ID it works fine.
{% assign collection = collections[‘TEST’] %}
{% assign product_ids = ‘8841905635651, 8841909403971’ | split: ', ’ %}
{% assign random_id = product_ids[1] %}
{{ random_id }}
{% for product in collection.products %}
{% if product.id == random_id %}
{% break %}
{% endif %}
{% endfor %}