设置GTM

Chrome 插件:

Tag Assistant
Google Analytic Debugger

在wordpress后台添加

使用插件:Google Site Kit | Code snipper | Custom Css & Js

header中添加

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','xxx-xxxxxxxx');</script>
<!-- End Google Tag Manager -->

body中添加

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TFN59S9T"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

添加DataLayer推送代码

// 1. 确定并记录用户ID(登录用户用WP用户ID,访客生成唯一ID并存Cookie)
function set_global_user_id(){
    global $ga4_user_id;
    if (is_user_logged_in()) {
        // 已登录:使用WordPress用户ID
        $ga4_user_id = (string) get_current_user_id();
    } else {
        // 未登录:检查或创建访客ID
        if (isset($_COOKIE['wp_guest_id'])) {
            $ga4_user_id = $_COOKIE['wp_guest_id'];
        } else {
            // 生成随机访客ID(保存一年)
            $ga4_user_id = bin2hex(random_bytes(8));
            setcookie('wp_guest_id', $ga4_user_id, time() + 31536000, "/");
        }
    }
}
add_action('init', 'set_global_user_id');
 
// 2. 在产品列表页推送 view_item_list 事件
function push_view_item_list_datalayer(){
    if (is_shop() || is_product_taxonomy()) {
        global $ga4_user_id, $wp_query;
        // 确定列表名称(商品分类名或商店页名)
        if (is_shop()) {
            $shop_page_id = wc_get_page_id('shop');
            $list_name = $shop_page_id ? get_the_title($shop_page_id) : 'All Products';
        } else {
            $term = get_queried_object();
            $list_name = $term ? $term->name : '';
        }
        $currency = get_option('woocommerce_currency');
        $items = array();
        $index = 0;
        if (!empty($wp_query->posts)) {
            foreach ($wp_query->posts as $post) {
                $product = wc_get_product($post->ID);
                if (!$product) continue;
                // 准备商品数据
                $item = array(
                    'item_id'   => $product->get_sku() ? $product->get_sku() : (string)$product->get_id(),
                    'item_name' => $product->get_name(),
                    'price'     => (float) $product->get_price(),
                    'quantity'  => 1
                );
                // 商品所属一级分类名称
                $terms = get_the_terms($product->get_id(), 'product_cat');
                if ($terms && !is_wp_error($terms)) {
                    $item['item_category'] = $terms[0]->name;
                }
                $item['index'] = $index;
                $items[] = $item;
                // 将该商品数据保存到全局JS对象,以供后续 add_to_cart 事件使用
                $item_for_map = $item;
                $item_for_map['currency'] = $currency;
                echo "<script>window.WooProducts = window.WooProducts || {};"
                   . "window.WooProducts['{$product->get_id()}'] = " 
                   . json_encode($item_for_map, JSON_UNESCAPED_UNICODE) . ";</script>";
                $index++;
            }
        }
        // 推送 view_item_list 事件到 DataLayer
        $push_data = array(
            'event'     => 'view_item_list',
            'ecommerce' => array(
                'item_list_name' => $list_name,
                'items'          => $items
            ),
            'user_id'   => $ga4_user_id
        );
        echo "<script>window.dataLayer = window.dataLayer || [];"
           . "window.dataLayer.push({\"ecommerce\": null});"
           . "window.dataLayer.push(" . json_encode($push_data, JSON_UNESCAPED_UNICODE) . ");</script>";
    }
}
add_action('woocommerce_after_shop_loop', 'push_view_item_list_datalayer');
 
// 3. 在产品详情页推送 view_item 事件
function push_view_item_datalayer(){
    if (is_product()) {
        global $ga4_user_id;
        global $product;
        if (!$product) $product = wc_get_product(get_the_ID());
        if (!$product) return;
        $currency = get_option('woocommerce_currency');
        // 当前产品数据
        $item = array(
            'item_id'   => $product->get_sku() ? $product->get_sku() : (string)$product->get_id(),
            'item_name' => $product->get_name(),
            'price'     => (float) $product->get_price(),
            'quantity'  => 1
        );
        $terms = get_the_terms($product->get_id(), 'product_cat');
        if ($terms && !is_wp_error($terms)) {
            $item['item_category'] = $terms[0]->name;
        }
        // 保存到全局JS对象,以供 add_to_cart 使用
        $item_for_map = $item;
        $item_for_map['currency'] = $currency;
        echo "<script>window.WooProducts = window.WooProducts || {};"
           . "window.WooProducts['{$product->get_id()}'] = " 
           . json_encode($item_for_map, JSON_UNESCAPED_UNICODE) . ";</script>";
        // 推送 view_item 事件
        $push_data = array(
            'event'     => 'view_item',
            'ecommerce' => array('items' => array($item)),
            'user_id'   => $ga4_user_id
        );
        echo "<script>window.dataLayer = window.dataLayer || [];"
           . "window.dataLayer.push({\"ecommerce\": null});"
           . "window.dataLayer.push(" . json_encode($push_data, JSON_UNESCAPED_UNICODE) . ");</script>";
    }
}
add_action('woocommerce_after_single_product', 'push_view_item_datalayer');
 
// 4. 在订单完成页推送 purchase 事件
function push_purchase_datalayer($order_id){
    if (!$order_id) return;
    global $ga4_user_id;
    $order = wc_get_order($order_id);
    if (!$order) return;
    $items = array();
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if (!$product) continue;
        // 订单中每件商品的数据
        $item_data = array(
            'item_id'   => $product->get_sku() ? $product->get_sku() : (string)$product->get_id(),
            'item_name' => $item->get_name(),
            'price'     => (float) ($item->get_total() / max(1, $item->get_quantity())),  // 每件商品实际支付单价
            'quantity'  => $item->get_quantity()
        );
        $terms = get_the_terms($product->get_id(), 'product_cat');
        if ($terms && !is_wp_error($terms)) {
            $item_data['item_category'] = $terms[0]->name;
        }
        $items[] = $item_data;
    }
    // 交易和金额信息
    $transaction_id = $order->get_order_number();
    $value    = (float) $order->get_total();
    $currency = $order->get_currency();
    $tax      = (float) $order->get_total_tax();
    $shipping = (float) $order->get_shipping_total();
    $coupon_codes = $order->get_coupon_codes();
    $coupon  = !empty($coupon_codes) ? implode(',', $coupon_codes) : '';
    // 准备 purchase 事件数据
    $purchase_data = array(
        'event'     => 'purchase',
        'ecommerce' => array(
            'transaction_id' => $transaction_id,
            'value'          => $value,
            'currency'       => $currency,
            'tax'            => $tax,
            'shipping'       => $shipping,
            'items'          => $items
        ),
        'user_id'   => $ga4_user_id
    );
    if ($coupon) {
        $purchase_data['ecommerce']['coupon'] = $coupon;
    }
    // 推送 purchase 事件到 DataLayer
    echo "<script>window.dataLayer = window.dataLayer || [];"
       . "window.dataLayer.push({\"ecommerce\": null});"
       . "window.dataLayer.push(" . json_encode($purchase_data, JSON_UNESCAPED_UNICODE) . ");</script>";
}
add_action('woocommerce_thankyou', 'push_purchase_datalayer', 10, 1);
 
// 5. 监听“添加到购物车”点击,推送 add_to_cart 事件
function add_to_cart_click_datalayer(){
    if (function_exists('is_product')) {
        global $ga4_user_id;
        $store_currency = get_option('woocommerce_currency');
        // 将 PHP 获取的 user_id 和货币代码嵌入 JS 脚本中
        $uid = $ga4_user_id ? $ga4_user_id : '';
        echo "<script>
        jQuery(function($){
            $('body').on('click', '.add_to_cart_button, .single_add_to_cart_button', function(){
                var productId = $(this).data('product_id') || $(this).closest('form').find('input[name=add-to-cart]').val();
                var qty = 1;
                if ($(this).closest('form').length) {
                    var qtyInput = $(this).closest('form').find('input[name=quantity]');
                    if (qtyInput.length) {
                        qty = parseInt(qtyInput.val()) || 1;
                    }
                } else {
                    var dataQty = $(this).data('quantity');
                    if (dataQty) {
                        qty = parseInt(dataQty) || 1;
                    }
                }
                if (productId) {
                    // 从全局对象中获取商品信息
                    var item = window.WooProducts && window.WooProducts[productId];
                    if (item) {
                        item.quantity = qty;
                    } else {
                        // 若未预先保存该商品信息(极少情况),则使用最基本信息
                        item = { item_id: productId, item_name: '', price: 0, quantity: qty };
                    }
                    var pushData = {
                        event: 'add_to_cart',
                        ecommerce: {
                            currency: item.currency || '$store_currency',
                            value: (item.price * qty) || 0,
                            items: [ item ]
                        },
                        user_id: '$uid'
                    };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push({ ecommerce: null });
                    window.dataLayer.push(pushData);
                }
            });
        });
        </script>";
    }
}
add_action('wp_footer', 'add_to_cart_click_datalayer');

Google Tag Manage 中设置Tag,Trigger,Variables

Tag

Tag:设置GA4 Configuration

Tag-Type:Google Tag
Tag ID:{{measurement-ID}} 这里使用Variable 的Const参数

Tag:设置Event Tag

Tag-Type:GA4 Event
Measurement-ID:{{measurement-ID}}
Event Parameter:设置需要传到GA4的参数,例:currency:{{Ecommerce Currency}}
trigger:使用与DataLayer推送代码中相同的事件名称,与下面Trigger名一致

Trigger

Trigger-Type:Custom Event
Event-Name:DataLayer推送代码中相同的事件名称

Variable

在GTM使用的变量与常量
设置Const参数 measurement-ID:GA代码::G-xxxxxxx
设置DataLayer Variable: user-id^[1]:user-id^[2]

[1]:使用Event Tag Parameter引用处相同的名称
[2]:使用DataLayer推送代码中的推送的变量名

Google Analytic 4设置

Debug VIew

查看调试数据
Admin Debug view

自定义参数:维度|指标

Admin Custom definition 添加自定义参数,例:使用ga-user-id代替保留关键字user-id

GTM 绑定Google Analytics & Google Ads

在wordpress 中添加

使用插件:GTM4WP - A Google Tag Manager (GTM) plugin for WordPress

SettingGoogle Tag Manager

General

Google Tag Manager ID: 填写GTM-xxxxxx
Container code ON/OFF: ON

Integration

Woocommerce:Track e-commerce 打钩

在Google Analytics中添加

Admin

产品链接 Google Ads 链接

在Google Tag Manager中添加

设置通用Tag与上面[[#Google Tag Manage 中设置Tag,Trigger,Variables#Tag|Tag]]一致