Uploading New Products with Multiple Variant Options

Shopify GraphQL: How to add multiple variants to a product?

I was defining the variants wrong. Without the options key (which is odd that it's plural considering it only takes a string?) it wouldn't work.

{
"input": {
"title": "Testing Products",
"handle": "test-product-2",
"variants": [
{
"title": "Size Small",
"options": "Small"
},
{
"title": "Size Medium",
"options": "Medium"
},
{
"title": "Size Large",
"options": "Large"
}
]
}
}

Shopify Multiple Product Options

It looks like you're missing the call to initialize the option selectors. That, combined with no default value for your variant drop-down, could be resulting in no valid ID being posted to Shopify when you try the Add-To-Cart.

One thing to do would be to automatically select the appropriate variant in your select-box. Shopify's product objects have a field called 'selected_or_first_available_variant', which comes in useful here. Example:

<option value="{{variant.id}}"  {% if variant == product.selected_or_first_available_variant %} selected {%endif %}>{{ variant.title }}</option>

(I often refer back to Shopify's excellent reference for Liquid objects, which can help give you ideas for what's possible)

If you're using Shopify's OptionSelectors, you may also need to make your variant ID field display:none - when OptionSelectors runs, it will automatically create 1-3 drop-downs for you based on the product's option dimensions.

For example: a product that comes in 3 different sizes and 2 different colours would have up to 6 different variants. Your initial select box will have all available combos as "Small / Red", "Small / Blue", "Medium / Red", etc.

Running the OptionSelectors code on the above example product would give you two selectors: one for size, one for colour. Under the hood, the OptionSelectors code takes the values of from each individual option-dimension (eg: "Small" and "Blue") to find the appropriate variant ID in the (hidden) master list.

To initialize Shopify's OptionSelectors, try adding this script tag immediately after your form to see if it helps:

{% if product.variants.size > 1 %}
<script>
function selectCallback(variant, selector){
// This is where you would put any code that you want to run when the variant changes.
}

var variantIdFieldIdentifier = 'variant-select';
new Shopify.OptionSelectors(variantIdFieldIdentifier, {
product: {{ product | json }}, // Product object required to know how options map to variants
onVariantSelected: selectCallback, // Function to do any interesting stuff (eg: update price field, image, etc) when selections change
enableHistoryState: true // When true, will update the URL to be a direct link to the currently-selected variant
})
</script>
{% endif %}


Related Topics



Leave a reply



Submit