Automatically select the first variant so products do not look sold out

This will apply to you if you're tracking stock levels, and your theme is using option_selection.js.

Why is this useful?

When a product is still available, yet its first variant is sold out, you will likely see a prominent SOLD OUT sign on your product page when you land on it:

Not sold out 1

Your customer may assume that your product is sold out and browse to another product page, or even leave your website. If they had clicked on the Size dropdown, they would have seen that your product is available in many sizes, some of them in stock. The customer needs to select another size to see if the product is available in that size. When a selection is made, your theme updates the price. When a selected variant is not defined, it will replace the price with “UNAVAILABLE”. When the variant is defined but sold out, it will replace the price with “SOLD OUT”.

If the customer is curious enough to select '140' in the dropdown, they will see a different picture:

Not sold out 2

The trouble is they might not click on that drop-down box and may have already moved on.

Here's the inventory for our product where the first variant is sold out:

Not sold out 3

The Solution

In plain English, we need to have the first available variant selected by default when we land on the product page. This is achieved using JavaScript and Liquid.

Start by locating Shopify's call to the Shopify.OptionSelectors constructor. It is often located in product.liquid near the bottom of the template. But in many themes, it is found in theme.liquid. It looks like this:

new Shopify.OptionSelectors("id", { product: {{ product | json }}, onVariantSelected: selectCallback });

Assign the value returned by new Shopify.OptionSelectors to a variable, and call selectVariant on it, like so:

jQuery(function() {
  var optionSelectors = new Shopify.OptionSelectors("id", { product: {{ product | json }}, onVariantSelected: selectCallback });
  // Grab the variant currently selected with ?variant=ID in the URL, or the first in stock variant, on page load.
  optionSelectors.selectVariant({{ }});

Want to discuss this page?

Visit the Shopify Community