# Shopifyでタグ設置

> Shopifyアプリとの連携設定については[Shopify連携](/integrations/shopify.md)もご覧ください。

## 基本タグの設置

### 1. theme.liquidテンプレートを見つける

Shopify管理画面で「Online Store」→「Themes」を選択し、「…」ボタンから「Edit code」を選択

### 2. \<head>の下にptengineの基本タグを設置

下記画像右側の赤枠の部分に、Ptengineの基本タグを貼り付けてください。

#### **基本タグの一例**

```js
<!-- Ptengine Tag -->
<script src="https://js.ptengine.com/xxxxxxxx.js"></script>
<!-- End Ptengine Tag -->
```

{% hint style="danger" %}
**⚠️注意**

上記xxxxxxxxの部分はプロジェクトのIDであり、Ptengineのプロジェクトごとに異なります。

自社プロジェクトのIDと書き換えてください。

詳しくは[こちらの記事](https://ptmind-1.gitbook.io/ptengine-helpcenter/start-guide/quick/tag-setting)をご参照ください。
{% endhint %}

#### **Ptengineの基本タグの取得方法**

{% embed url="<https://app.arcade.software/share/9Co1auPt7xkZweCU7ehH>" %}

## イベントの設置

上記基本タグを設置するのみで、**購買完了、カートイン**などECサイトでよくある行動データの集計ができません。

そのため、Ptengine上でもイベントデータやCVデータを確認したい場合、イベントの設置もおすすめです。

### イベント収集タグの導入

#### 1、Shopify管理画面で「Settings」を選択

#### 2、「Customer events」を選択

#### 3、Pixel nameをつける

右上の黒いボタン「Add custom pixel」をクリックし、ポップアップの中でpixel nameを設定します。（下記図はサンプルとして「pt tracking on checkouts」という名前をつけております）

そしてAdd pixelをクリックしてください。

#### 4、保存

Codeに下記コードを貼り付けて、右上の「save」で保存します。

{% hint style="danger" %}
**⚠️注意**

**必ず**　`const sid`　**に自社PtengineのプロジェクトIDに置き換えてください！！！**
{% endhint %}

```js
// 貼り付け用コード
function trackEvent(eventType, eventProperties, cb) {
  const sid = "プロファイルidを入力してください";
  // プロジェクトIDを入れてください！
  const area = "jp";
  const options = eventProperties || {};

  loadPtengineScript(sid, area)
    .then(() => {
      console.log("ptengineスクリプトの読み込み完了");
      window.ptengine && window.ptengine.track(eventType, options);
      cb && typeof cb === "function" && cb();
    })
    .catch((error) => {
      console.error("ptengineスクリプトの読み込み失敗:", error);
    });
}

function loadPtengineScript(sid, area) {
  return new Promise((resolve, reject) => {
    if (window.ptengine) {
      resolve();
    } else {
      const url = window.location.href.replace(
        /\/wpm@[a-zA-Z0-9]+\/web-pixel-[a-zA-Z0-9]+@[a-zA-Z0-9]+\/sandbox\/modern/,
        ""
      );
      window._pt_sp_2 = [];
      _pt_sp_2.push(`setAccount, ${sid}`);
      _pt_sp_2.push(`setPVTag,${url},replace`);

      const script = document.createElement("script");
      const isCheckoutPage = window.location.href.includes("checkouts");
      const sandboxQuery = isCheckoutPage ? "" : "?sandbox";
      script.src = `https://js.ptengine.${area}/${sid}.js${sandboxQuery}`;
      script.onload = () => resolve();
      script.onerror = () => reject(new Error("Script loading failed"));
      document.head.appendChild(script);
    }
  });
}

analytics.subscribe("checkout_completed", (event) => {
  const checkout = event?.data?.checkout;
  const checkoutTotalPrice = checkout?.totalPrice?.amount;
  const checkoutItems = checkout?.lineItems;
  const checkoutOrderId = checkout?.order?.id;
  const uid = event?.data?.clientId;

  const eventProperties = {
    totalPrice: checkoutTotalPrice,
    totalorderid: checkoutOrderId,
  };

  const identifyCallback = () => {
    checkoutItems.forEach((checkoutItem) => {
      ptengine &&
        ptengine.identify(uid, {
          totalPrice: checkoutTotalPrice,
          totalorderid: checkoutOrderId,
          totalquantity: checkoutItem?.quantity,
          totaltitle: checkoutItem?.title,
          totalid: checkoutItem?.id,
          totalsku: checkoutItem?.variant?.sku,
          totalProductType: checkoutItem?.variant?.product?.type,
        });
    });
  };
  trackEvent("checkout_completed", eventProperties, identifyCallback);
});

analytics.subscribe("search_submitted", (event) => {
  trackEvent("search_submitted");
});

analytics.subscribe("collection_viewed", (event) => {
  trackEvent("collection_viewed");
});

analytics.subscribe("product_viewed", (event) => {
  trackEvent("product_viewed");
});

analytics.subscribe("product_added_to_cart", (event) => {
  trackEvent("product_added_to_cart");
});

analytics.subscribe("product_removed_from_cart", (event) => {
  trackEvent("product_removed_from_cart");
});

analytics.subscribe("cart_viewed", (event) => {
  trackEvent("cart_viewed");
});

analytics.subscribe("checkout_started", (event) => {
  trackEvent("checkout_started");
});

analytics.subscribe("checkout_contact_info_submitted", (event) => {
  trackEvent("checkout_contact_info_submitted");
});

analytics.subscribe("checkout_address_info_submitted", (event) => {
  trackEvent("checkout_address_info_submitted");
});

analytics.subscribe("checkout_shipping_info_submitted", (event) => {
  trackEvent("checkout_shipping_info_submitted");
});

analytics.subscribe("payment_info_submitted", (event) => {
  trackEvent("payment_info_submitted");
});

```

#### 5、公開

最後に右上の「Connect」ボタンを押してStep4で設置したコードを公開します。

### イベントタグの発火タイミングについて

<table><thead><tr><th width="318.41796875">イベント名</th><th>発火タイミング</th></tr></thead><tbody><tr><td>search_submitted</td><td>検索機能を使用した際</td></tr><tr><td>collection_viewed</td><td>一覧ページを閲覧した際</td></tr><tr><td>product_viewed</td><td>商品詳細ページを閲覧した際</td></tr><tr><td>product_added_to_cart</td><td>カートに商品を追加した際</td></tr><tr><td>product_removed_from_cart</td><td>カートから商品を削除した際</td></tr><tr><td>cart_viewed</td><td>カートページを閲覧した際</td></tr><tr><td>checkout_started</td><td>Checkoutページへ遷移した際</td></tr><tr><td>checkout_contact_info_submitted</td><td>連絡先（メールアドレス）を入力した際</td></tr><tr><td>checkout_address_info_submitted</td><td>住所情報を入力した際</td></tr><tr><td>checkout_shipping_info_submitted</td><td>配送方法を選択した際</td></tr><tr><td>payment_info_submitted</td><td>支払い方法を選択した際</td></tr><tr><td>checkout_completed</td><td>支払いが完了した際</td></tr></tbody></table>

## 注意事項

ShopifyでPtengineをご利用いただく際は、以下の点を必ずご確認ください。

### **1. Ptengineの基本タグは「Shopifyのテーマ」に直接設置してください**

Ptengineの基本タグは、Shopifyのテーマ（theme.liquid）へ直接設置してください。

Google Tag Manager経由での設置は、Shopifyの仕様上イベント計測ができない場合がございます。

そのため、GTMなどなどのタグマネージャーの経由での設置は推奨しておらず、サポート対象外となります。

### **2. ページ単位の送信制限や条件追加をしないでください**

Ptengine の基本スクリプトをアレンジし特定ページのみで発火させることやURL条件などで発火を制限することを推奨しておりません。

その状態で発生したデータ計測の不具合については、原因調査やサポート対応ができかねますのでご了承ください。

### **3. テーマを変更した場合は、再度タグ設置が必要です**

Shopifyでは、テーマを変更すると theme.liquid の内容がリセットされます。

そのため、テーマの切り替えや新しいテーマの適用を行った場合、

新しいテーマにもPtengineの基本タグを再度設置してください。

タグを再設置しない場合、Ptengineの計測は行われませんのでご注意ください。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://helps.ptengine.com/start-guide/othertag/tag-shopify.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
