How can I retrieve product details using variant id?

Dear all,

I have a list of variants in schema with their IDs and the user should be able to choose any of those using drop down box so he can dynamically change the product and its variant inside a frame. Now, I have been stucked in finding a way to get product title, price and other details using variant Id listed in the schema. I would really appreciate for any kind of suggestion. Thank you.

I’m not sure whether you mean Javascript or Liquid, so I’m assuming it’s javascript.

You can always add a .json at the end of the product page to get the product information. For example, in this product page:

https://row.gymshark.com/products/gymshark-apex-sports-bra-light-teal

You can access the information adding .json at the end:

https://row.gymshark.com/products/gymshark-apex-sports-bra-light-teal.json

Now you just need to make a function to get the data you need. I’d do something like this:

async function _getCurrentProduct() {

        const url = `https://${window.location.host + window.location.pathname}.json`;

        return new Promise(async (resolve, reject) => {

            let response = await fetch(url);

            let {
                product
            } = await response.json();

            resolve(product);
        });
    }
1 Like

Thank you for your reply. Actually I was looking for the solution/suggestion in Liquid.

1 Like

For liquid just use the documentation:

https://shopify.dev/docs/themes/liquid/reference/objects/product

This does not answer the question

For a liquid alternative, you can do this. However, I’d still highly recommend using AJAX for the sake of performance:

{% assign variant_id_to_find = 123456789 %}

{% for product in collections.all.products %}
  {% for variant in product.variants %}
    {% if variant.id == variant_id_to_find %}
      {% assign found_product = product %}
    {% endif %}
  {% endfor %}
{% endfor %}

{% if found_product %}
  

Product found: {{ found_product.title }}

{% else %}
  

Product not found

{% endif %}

Best,
Diego