You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce加购事件跟踪如何获取选中变体SKU写入数据层

WooCommerce可变商品加购跟踪获取变体SKU实现方案

你可以通过监听WooCommerce自带的变体选中事件实现动态获取选中的SKU,修改后的完整代码如下:

function pixel_tracker() {
    if( is_wc_endpoint_url('order-received') ) return;
    if( is_product() ){
?>

    <!-- Glami piXel -->
        <script>
        (function(f, a, s, h, i, o, n) {f['GlamiTrackerObject'] = i;
        f[i]=f[i]||function(){(f[i].q=f[i].q||[]).push(arguments)};o=a.createElement(s),
        n=a.getElementsByTagName(s)[0];o.async=1;o.src=h;n.parentNode.insertBefore(o,n)
        })(window, document, 'script', '//www.glami.sk/js/compiled/pt.js', 'glami');

        glami('create', 'AADAD885F5F5FF4D', 'sk');
        glami('track', 'PageView');
        
<?php 
        /*Product view */
        if( is_product() ){
        global $post;
        $product = wc_get_product( $post->ID );
        
    
?>  
        /*View content type product*/
        glami('track', 'ViewContent', {
        content_type: 'product',
        item_ids: ['<?php echo $product->get_sku(); ?>'],
        product_names: ['<?php echo $product->get_name(); ?>'] 
        });
        
        /*Add to cart*/ 
        jQuery( document ).ready(function() {
            // 存储当前选中的变体信息
            let current_selected_variation = {};
            // 监听变体选中事件,实时更新变体数据
            jQuery('form.variations_form').on('found_variation', function(event, variation) {
                current_selected_variation = variation;
            });
            // 监听变体重置事件,清空存储的变体数据
            jQuery('form.variations_form').on('reset_data', function() {
                current_selected_variation = {};
            });

            jQuery(".single_add_to_cart_button").click(function(){
                // 优先取变体SKU,不存在则用主商品SKU
                let sku = current_selected_variation.sku ? current_selected_variation.sku : '<?php echo $product->get_sku(); ?>';
                // 优先取变体价格,不存在则用主商品价格
                let price = current_selected_variation.display_price ? current_selected_variation.display_price : <?php echo $product->get_price(); ?>;
                glami('track', 'AddToCart', {
                    item_ids: [sku],
                    product_names: ['<?php echo $product->get_name(); ?>'],
                    value: price,
                    currency: 'EUR'
                    });
                });
            });

<?php
        }
?>

        </script>
    <!-- End Glami piXel -->
    
<?php
}
}
add_action('wp_head', 'pixel_tracker');

实现逻辑说明

  • 利用WooCommerce可变商品页原生的found_variation事件,用户选择完所有变体属性触发匹配后,自动将变体完整信息存入全局变量
  • 加购事件触发时优先读取已存储的变体SKU和价格,若不存在匹配变体(简单商品场景、用户未选全变体属性)自动降级使用主商品数据
  • 无需额外修改主题或插件代码,兼容所有标准WooCommerce可变商品模板

内容的提问来源于stack exchange,提问作者Lubo Masura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:15:01