简体   繁体   中英

How do I create a product with a metafield using a single API call?

For a Shopify store I want to create a product with a metafield using a single API call.

Here's what I'm trying:

require 'shopify_api'

ShopifyAPI::Base.site =  "https://<REDACTED>:<REDACTED>@<REDACTED>.myshopify.com/admin";

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123',
    "metafields" => [
      {
        "key" => "item_size",
        "value" => '125gr',
        "value_type" => "string",
        "namespace" => "global"
      }
    ]
  }
]

new_product.save

new_product.metafields
# => #<ActiveResource::Collection:0x007f8de3bf9820
 @elements=[],
 @original_params={},
 @resource_class=ShopifyAPI::Metafield>

But this doesn't work.

I know I could do the following:

require 'shopify_api'

ShopifyAPI::Base.site =  "https://<REDACTED>:<REDACTED>@<REDACTED>.myshopify.com/admin"

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123'
  }
]

new_product.save

new_product.add_metafield(ShopifyAPI::Metafield.new(:namespace => "global", :key => "item_size", :value => "125gr", :value_type => "string"))

new_product.metafields

But since I have to import ~26000 product and there is a API call limit of 2 per second I need be as efficient as possible.

What could I try next?

Shayne, a Shopify employee pointed out :

It looks like you're putting the metafield on the variant in that example, and then at the end you're looking on the product to see if there are any metafields present. Both products and variants can have metafields, but if you put the metafield on the variant, that's where it will stay.

Here's how to create a product with a product metafield:

require 'shopify_api'

ShopifyAPI::Base.site =  "https://<REDACTED>:<REDACTED>@<REDACTED>.myshopify.com/admin"

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123'
  }
]

new_product.metafields = [
  {
    "key" => "item_size",
    "value" => '125gr',
    "value_type" => "string",
    "namespace" => "global"
  }
]

new_product.save

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM