Ad

In Shopify Add A Product Via SKU Rather Than Variant ID

- 1 answer

I know in Shopify you can add a product to cart with the variant ID like this:

/cart/add?id=VARIANT_ID

I'm trying to find a way to add it by SKU instead, something like this:

/cart/add?sku=SKU

That would be much easier, our SKU's never change.

If that's not possible is there a way to discover the variant id based on SKU?

Ad

Answer

You always buy a variant in Shopify.

The order itself keeps a record to the variant ID as a reference point.

So the short answer is NO - you can't add a product via a SKU.

For you second question:

is there a way to discover the variant id based on SKU?

Yes but it really depends how are you implementing the SKU part.

If you are on the product page and you have the SKU then you can get the variant_id if you filter out the variants.

But if you are not on the product page and you have for example 500+ products, then the fastest way will be to use GraphQL like so:

{ 
  productVariants(first: 1, query: "sku:SOMESKU"){
    edges {
      node {
        id
      }
    }
  }
}

Where it will return a result such as:

{
  "data": {
    "productVariants": {
      "edges": [
        {
          "node": {
            "id": "gid://shopify/ProductVariant/14726421905460"
          }
        }
      ]
    }
  },
  "extensions": {
    "cost": {
      "requestedQueryCost": 3,
      "actualQueryCost": 3,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 997,
        "restoreRate": 50
      }
    }
  }
}

And you will pass the returned variant ID to the cart instead.

Ad
source: stackoverflow.com
Ad