Tuesday, 24 December 2019

How to include variant price in variant select dropdown while retaining option_selection.js

I'm using shopify and would like to show the variant price in the variant selector dropdown. Shopify uses an asset named option_selection.js to implement variant selection features. This asset is necessary for proper operation of the site; however, this asset overwrites the select tag that is created in the product.liquid file.

Without option_selection.js included, you can simply add the variant price to each option in the product.liquid file. Something like this:

<div class="variants-wrapper clearfix "> 
    <select id="product-select" name="id">
        
    </select>
</div>

However, with option_selection.js enabled, this select dropdown is replaced with a different one containing only the variant title and no other information.

After some trial and error I found that I could overwrite Shopify.Product.prototype.optionValues in a script tag placed directly after the option_selection.js script tag with the following snippet:

Shopify.Product.prototype.optionValues = function(o) {
  if (!Shopify.isDefined(this.variants)) return null;
  var t = Shopify.map(this.variants, function(t) {
    var e = "option" + (o + 1);
    if(t[e] == undefined) {
      return null
    } else {
      var value = t[e] + " - " + Shopify.formatMoney(t.price)
      if(!t.available) value += " - No Stock"
      return value
    }
  });
  return null == t[0] ? null : Shopify.uniq(t)
}

That snippet overwrites the following snippet:

Shopify.Product.prototype.optionValues = function(o) {
    if (!Shopify.isDefined(this.variants)) return null;
    var t = Shopify.map(this.variants, function(t) {
        var e = "option" + (o + 1);
        return t[e] == undefined ? null : t[e]
    });
    return null == t[0] ? null : Shopify.uniq(t)
}

However, this causes the rest of the features implemented in option_selection.js to stop working entirely. I don't understand why this change should affect the rest of the script, but it does.

To test for this, you can create an item with two variants, one available and one unavailable. Selecting the available item should enable the "Add to cart" button, while selecting the unavailable option should disable the button. This is one of many features implemented by option_selection.js that fails once this attempted fix is implemented.

How can I go about including the variant price in the variant select dropdown while retaining option_selection.js and its features?




from How to include variant price in variant select dropdown while retaining option_selection.js

No comments:

Post a Comment