How do I get the variant ID of a product I'm currently viewing? For example, if I'm viewing a product at example.com/collections/bowls/product-name?variant=123456789
I need to get the variant's ID number. I've tried {{ variant.id }}
but it does not return anything. I can get it to return all of the variant ID's when I put it within a {% for variant in product.variants %}
loop but that returns all of the IDs. I just need the ID of the one I'm currently viewing.
Asked
Active
Viewed 1.2k times
1

Dustin
- 4,314
- 12
- 53
- 91
2 Answers
1
{{ product.selected_variant.id }}

Dustin
- 4,314
- 12
- 53
- 91
-
1You might actually want to use `product.selected_or_first_available_variant.id` - as I understand it, `selected_variant` is null if there's no variant in the URL of the page you are on. – Dave B Aug 17 '17 at 16:29
-
{{ product.selected_variant.id }} is the correct answer – Sahib Khan Dec 20 '22 at 22:45
0
if you are using javascript you can get variant id of selected variant from the product page with querySelector.
document.querySelector('.product__pickup-availabilities').dataset.variantId
it works for both conditions(with variants or not),