I would like to get a product by ID but I don’t know how to do that.
The product ID is 2
Please don’t tell me “you can use all_products” using this code:
{% for product in collections.all.products %}
{% if product.id == 2 %}
{% assign my_product = product %}
{% endif %}
{% endfor %}
or:
{{ all_products['2'] }}
I cannot use “all_products” because I have many many products (10000 products).
And I cannot create many many many collections only to get product by id.
Indeed : The all_products object has a limit of 20 unique handles per page. If you want more than 20 products, then consider using a collection instead.
Product by id is good way to get product info and also instead of using “if” please use “case” so best code practice and fast result while searching on loop of around 50 iterations.
Good suggestion for switch/case but yours had some typos. The following works for me when inserting as custom liquid block during WYSWYG customization:
{% for product in collections.all.products %}
{% case product.id %}
{% when 123456 %}
{% assign my_product = product %}
{% endcase %}
{% endfor %}
You can use the ‘where’ filter on the desired products collection, just make sure you that you cast the id as an integer rather than a string. In this example the id is coming from a text theme-setting, so I cast it to an integer by applying times: 1
Isn’t this still subject to the same limit of 1000 products? Or does the “where” filter have some special permission where it’ll search the entire collection of more than 1000 products (e.g. if it was 10,000 or more).