Reputation: 21
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 DIV. 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. Please check the image for more detail
Upvotes: 2
Views: 11366
Reputation: 3248
Are you trying to use this information in a merchant-facing app or the customer-facing storefront?
Assuming the latter (as your screenshot shows the theme/section settings in Shopify), there is no way to get a variant object just from its ID, and even if you could there is no way to easily move from a variant object to a product object in Shopify.
You will need to also collect the associated product handles for the product objects that you want to work with. Once you have a product handle, you can get the product object using Liquid or Javascript quite easily.
Assuming that you have a product handle saved to a variable named product_handle
and the variant ID saved to a variable named variant_id
, the code could look something like:
Liquid
{% assign product = all_products[product_handle] %}
{% assign variant = product.variants | where: 'id', variant_id | first %}
Javascript
// Retrieve the product data using Shopify's frontend API endpoint
fetch('/products/' + product_handle + '.js').then(function(response){ return response.json() }).then(
function(product){
let variant = product.variants.find(function(variant){ return variant.id == variant_id })
// Do stuff with your product & variant objects
}
)
Upvotes: 5