Converting SKU to Variant ID before doing cart.push

Converting SKU to Variant ID before doing cart.push

afcompany
Shopify Partner
17 0 9

We have built a JS config file that is a collection of items that make up a completed product. This file is included into the AddItem JS file. Each item has to have Variant ID, but since we have multiple sites, that Variant ID changes from site to site. I want to use SKU to simplify across all sites when building the JS config file.

 

Is there a way to convert SKU to Product ID just before submitting the cart.push command in the AddItem JS file? 

 

I was thinking that we could query a collection and get the Variant ID based on the SKU. Then assign the Variant ID in the cart.push instead of the SKU.

 

Any thoughts on this?

Reply 1 (1)

Small_Task_Help
Shopify Partner
986 39 93

Hi,

Hope this will help

-Add JavaScript function to get Variant ID using SKU

Code example

async function getVariantIdBySKU(sku) {
  const response = await fetch('/products.json');
  const data = await response.json();

  for (const product of data.products) {
    for (const variant of product.variants) {
      if (variant.sku === sku) {
        return variant.id;
      }
    }
  }

  return null; // Not found
}


-Update your cart.push logic

To Get Shopify Experts Help, Click Here or E-mail - hi@ecommercesmalltask.com
About Us - We are Shopify Expert India
At Google My Business - Ecommerce Small Task - Hire Shopify Developers Ahmedabad