mcpField
S
shopify-metafields

shopify-metafields

github.com/finsilabsデータ・データベース6077 回インストール5 日前に更新
リポジトリ

shopify-metafields について

metafields と Metaobjects を使い、Shopify の各リソースに構造化されたカスタムデータを追加するガイドです。独自のストアフロントやコンテンツセクションを構築する開発者向けに、定義、API での読み書き、Liquid 表示、型検証を扱います。

主な機能

  1. 01Shopify リソースへの構造化データ追加
  2. 02定義によるフィールド型の検証
  3. 03Admin API による metafields の書き込み
  4. 04Liquid と Storefront API でのデータ参照
  5. 05再利用可能な Metaobjects の作成

活用シーン

  1. 01商品に寸法、ケア情報、認証を追加
  2. 02顧客ランクや注文の配送指示を保存
  3. 03テーマ内で FAQ やサイズガイドを管理
  4. 04再利用可能なチーム情報や仕様項目を作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/finsilabs/awesome-ecommerce-skills --skill shopify-metafields

インストール後、Claude Code で/shopify-metafieldsを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

tile.json
evals/metafield-definitions-and-bulk-write/
criteria.json
task.md
evals/metaobjects-for-structured-content/
criteria.json
task.md
evals/storefront-api-metafield-queries/
criteria.json
task.md

詳細

Shopify メタフィールド

概要

メタフィールドを使うと、別のデータベースを構築することなく、商品、バリエーション、注文、顧客、コレクション、ページなどの Shopify リソースに構造化されたカスタムデータを追加できます。メタフィールド定義では型の検証(テキスト、数値、日付、URL、JSON、ファイル、商品参照など)が行われ、Liquid テンプレートエディターや Storefront API でメタフィールドを利用できるようになります。メタオブジェクトはこの概念を拡張し、再利用可能な独立したカスタムデータ構造を作成します。

このスキルを使う場面

  • 商品に、Shopify のデフォルトのフィールド以外の属性(お手入れ方法、寸法、認証など)が必要な場合
  • ロイヤルティティア、サブスクリプションのステータス、B2B アカウント番号など、顧客ごとのデータを保存する場合
  • メタフィールド参照を使って、テーマ内にコンテンツ管理可能なセクション(FAQ、サイズガイド、機能の紹介など)を構築する場合
  • チェックアウトから注文単位のカスタムデータ(ギフトメッセージ、配送指示など)を追加する場合
  • メタオブジェクトを使って、再利用可能な構造化コンテンツのエントリー(チームメンバー、プレス掲載情報、仕様など)を作成する場合

基本的な指示

  1. Admin API でメタフィールド定義を作成します

    定義によって型が検証され、メタフィールドをストアフロントから利用できるようになります。

    // Create a metafield definition for product care instructions
    const response = await adminClient.request(`
      mutation CreateMetafieldDefinition($definition: MetafieldDefinitionInput!) {
        metafieldDefinitionCreate(definition: $definition) {
          createdDefinition {
            id
            name
            namespace
            key
            type { name }
          }
          userErrors { field message code }
        }
      }
    `, {
      variables: {
        definition: {
          name: "Care Instructions",
          namespace: "custom",
          key: "care_instructions",
          type: "multi_line_text_field",
          ownerType: "PRODUCT",
          description: "Washing and care instructions for the product",
          visibleToStorefrontApi: true,
          // Optional: pin to product admin UI (use pinnedPosition in API version 2023-10+)
          pinnedPosition: 1,
        },
      },
    });
    

    利用可能な型:single_line_text_field、multi_line_text_field、number_integer、number_decimal、date、date_time、boolean、url、json、color、weight、volume、dimension、rating、file_reference、product_reference、variant_reference、collection_reference、page_reference、metaobject_reference、list.<type>。

  2. Admin API でメタフィールドを書き込みます

    // Set a metafield on a product
    export async function setProductMetafield(
      productId: string,
      namespace: string,
      key: string,
      value: string,
      type: string
    ) {
      const response = await adminClient.request(`
        mutation SetMetafield($metafields: [MetafieldsSetInput!]!) {
          metafieldsSet(metafields: $metafields) {
            metafields {
              id key namespace value
            }
            userErrors { field message code }
          }
        }
      `, {
        variables: {
          metafields: [
            {
              ownerId: productId,
              namespace,
              key,
              value,
              type,
            },
          ],
        },
      });
      return response.data.metafieldsSet;
    }
    
    // Example: Set care instructions on a product
    await setProductMetafield(
      "gid://shopify/Product/1234567890",
      "custom",
      "care_instructions",
      "Machine wash cold. Tumble dry low. Do not bleach.",
      "multi_line_text_field"
    );
    
  3. Liquid テンプレートでメタフィールドを読み取ります

    visibleToStorefrontApi: true の定義を作成すると、metafields オブジェクトを通じて Liquid でメタフィールドを利用できます。

    {% comment %} product.metafields.namespace.key {% endcomment %}
    
    {% if product.metafields.custom.care_instructions != blank %}
      <div class="care-instructions">
        <h3>Care Instructions</h3>
        {{ product.metafields.custom.care_instructions | metafield_tag }}
      </div>
    {% endif %}
    
    {% comment %} Access a product reference metafield {% endcomment %}
    {% assign related = product.metafields.custom.related_product.value %}
    {% if related %}
      <a href="{{ related.url }}">{{ related.title }}</a>
    {% endif %}
    
    {% comment %} Access a list of file references (images) {% endcomment %}
    {% for image in product.metafields.custom.gallery_images.value %}
      <img src="{{ image | image_url: width: 800 }}" alt="{{ image.alt }}">
    {% endfor %}
    
  4. Storefront API でメタフィールドを読み取ります

    // Query product with metafields in the Storefront API
    const { data } = await storefront.request(`
      query GetProductWithMetafields($handle: String!) {
        product(handle: $handle) {
          id
          title
          # Metafields must be explicitly requested by namespace + key
          careInstructions: metafield(namespace: "custom", key: "care_instructions") {
            value
            type
          }
          relatedProduct: metafield(namespace: "custom", key: "related_product") {
            reference {
              ... on Product {
                id title handle
                featuredImage { url altText }
              }
            }
          }
          certifications: metafield(namespace: "custom", key: "certifications") {
            references(first: 5) {
              edges {
                node {
                  ... on Metaobject {
                    id
                    fields {
                      key value
                    }
                  }
                }
              }
            }
          }
        }
      }
    `, { variables: { handle: "my-product" } });
    
  5. メタオブジェクトを作成して使用します

    メタオブジェクトは独立したカスタムデータのエントリーで、FAQ、推薦文、その他の構造化コンテンツに便利です。

    // Create a Metaobject definition
    await adminClient.request(`
      mutation {
        metaobjectDefinitionCreate(definition: {
          name: "FAQ Entry"
          type: "faq_entry"
          fieldDefinitions: [
            { name: "Question", key: "question", type: "single_line_text_field", required: true }
            { name: "Answer", key: "answer", type: "multi_line_text_field", required: true }
            { name: "Sort Order", key: "sort_order", type: "number_integer" }
          ]
        }) {
          metaobjectDefinition { id type }
          userErrors { field message }
        }
      }
    `);
    
    // Create a Metaobject entry
    await adminClient.request(`
      mutation {
        metaobjectCreate(metaobject: {
          type: "faq_entry"
          fields: [
            { key: "question", value: "What is your return policy?" }
            { key: "answer", value: "We accept returns within 30 days of purchase." }
            { key: "sort_order", value: "1" }
          ]
        }) {
          metaobject { id handle }
          userErrors { field message }
        }
      }
    `);
    

例

商品属性のメタフィールドを一括インポートする
// Import dimensions for multiple products at once (up to 25 per request)
export async function bulkSetDimensions(
  products: Array<{ id: string; weight: number; length: number; width: number; height: number }>
) {
  const metafields = products.flatMap(({ id, weight, length, width, height }) => [
    { ownerId: id, namespace: "custom", key: "weight_grams", value: weight.toString(), type: "number_integer" },
    { ownerId: id, namespace: "custom", key: "length_cm", value: length.toString(), type: "number_decimal" },
    { ownerId: id, namespace: "custom", key: "width_cm", value: width.toString(), type: "number_decimal" },
    { ownerId: id, namespace: "custom", key: "height_cm", value: height.toString(), type: "number_decimal" },
  ]);

  // Process in batches of 25 (API limit)
  for (let i = 0; i < metafields.length; i += 25) {
    const batch = metafields.slice(i, i + 25);
    await adminClient.request(`
      mutation SetMetafields($metafields: [MetafieldsSetInput!]!) {
        metafieldsSet(metafields: $metafields) {
          userErrors { field message }
        }
      }
    `, { variables: { metafields: batch } });
  }
}
Liquid で FAQ のメタオブジェクトをレンダリングする
{% comment %} sections/faq.liquid {% endcomment %}
{% assign faqs = shop.metafields.custom.faq_entries.value %}

<div class="faq-section">
  <h2>Frequently Asked Questions</h2>
  {% for faq in faqs %}
    <details class="faq-item">
      <summary>{{ faq.question.value }}</summary>
      <div class="faq-answer">{{ faq.answer.value | newline_to_br }}</div>
    </details>
  {% endfor %}
</div>

ベストプラクティス

  • メタフィールドを書き込む前に必ず定義を作成します — 定義により型の検証、ストアフロント API からのアクセス、Admin UI のフィールドエディターが利用可能になります。未定義の namespace/key の組み合わせは、そのまま JSON として表示されます
  • マーチャントが管理するデータには custom 名前空間を使用します — その他の名前空間(例:app_name)は、マーチャントが直接編集すべきではないアプリ所有のデータ用に確保します
  • テーマやヘッドレスフロントエンドで読み取る必要がある定義には、visibleToStorefrontApi: true を設定します — メタフィールドはデフォルトで非公開です
  • metafieldsSet でメタフィールドの書き込みをまとめて行います — 1 回のミューテーションで最大 25 個のメタフィールドを受け付けます。一括操作では、個別の productUpdate 呼び出しではなくこれを使用します
  • リッチテキストやファイル参照のメタフィールドには、Liquid の metafield_tag フィルターを使用します — メタフィールドの型に応じて、適切な HTML 要素(img、p など)をレンダリングします
  • 複数のフィールドを持つ構造化データには、JSON メタフィールドよりメタオブジェクトを優先します — メタオブジェクトは型が厳密で、Shopify Admin UI でコンテンツを編集できます
  • 名前空間を文書化します — 規則(マーチャント用は custom.*、アプリ用は yourapp.* など)を定め、開発者がキーを確認できるよう、使用するキーを文書化します

よくある問題

問題解決策
Storefront API でメタフィールドが null を返すメタフィールド定義で visibleToStorefrontApi: true を設定する必要があります。このフラグなしで作成されている場合は、定義を更新してください
Liquid で metafields.custom.key が空になるnamespace/key の定義が存在することを確認してください。Liquid で公開されるのは、登録済みの定義があるメタフィールドのみです
リスト型メタフィールドの値が配列ではなく JSON 文字列になるLiquid では `
metafieldsSet が TYPE_MISMATCH で失敗するvalue は型に一致する JSON シリアライズ済み文字列である必要があります。number_integer の場合は 42 ではなく "42" を渡してください
Metaobject のフィールドが更新されないMetaobject GID を指定して metaobjectUpdate ミューテーションを使用し、fields 配列を渡してください。一部のフィールドのみの更新も可能です
アプリの namespace が別のアプリと競合する共有ストアでの競合を避けるため、namespace のプレフィックスとしてアプリのハンドル(例:myapp-handle)を使用してください

関連スキル

  • @shopify-admin-api
  • @shopify-storefront-api
  • @shopify-app-development
  • @shopify-theme-development
  • @custom-product-attributes

コメント