追踪 Woocommerce 添加到购物车

问题描述 投票:0回答:3

我正在寻找一种方法来跟踪 woocommerce 中的添加到购物车事件,将数据推送到几个数据层(产品名称、数量、价格和 sku),以便我可以在 google 标签管理器中跟踪它们。我们对 php 还很陌生,我似乎无法在网上找到任何示例。您能建议一个解决方案吗?

php woocommerce tracking cart
3个回答
0
投票

好吧,我想出了几个选择。

选项#1

这不是一个非常干净的方法,但应该不会有太多麻烦。这个想法是绑定

.single_add_to_cart_button
来执行 AJAX 请求,这样您就可以将产品页面中的所有可见数据传输到 PHP 数组。

将此JS添加到产品页面:

jQuery( '.single_add_to_cart_button' ).click( function( event ) {
    event.preventDefault();
    jQuery.ajax({
        url: '/path/to/wp-admin/admin-ajax.php',
        type: 'POST',
        data: {
            action: 'get_add_to_cart_data',
            sku: jQuery( '...' ) // extract the data you want from the page
        }
        success: function( response ) {
            console.log( response ); // log errors
            jQuery( '.single_add_to_cart_button' ).unbind( 'click' ).click(); // now add to cart
        }
    });
});

然后,作为服务器端 PHP:

function get_add_to_cart_data() {
    $sku = $_POST['sku']; // all your data will be in this array
    track(); // do whatever to track the data
    echo "Success";
}
// Now bind this function to use with AJAX in WordPress
add_action( 'wp_ajax_get_add_to_cart_data', 'get_add_to_cart_data' );
add_action( 'wp_ajax_nopriv_get_add_to_cart_data', 'get_add_to_cart_data' );

选项#2

我更喜欢这个想法,但我还没有完全测试过。您将使用

woocommerce_add_cart_item
过滤器,在 PHP 中使用如下所示的内容:

function track_cart_item( $cart_array ) {
    track( $cart_array ); // this array should contain most (all?) the data you want to use
}
add_filter( 'woocommerce_add_cart_item', 'track_cart_item', 10, 1 );

0
投票

我写了一篇简短的教程文章来涵盖这个主题:

sampovirmasalo.fi - 使用此 Google 跟踪代码管理器代码片段跟踪 WooCommerce 中的“添加到购物车”事件

基本思想是为单个产品页面上的“添加到购物车”按钮添加跟踪事件,并在产品列表和轮播中添加“添加到购物车”链接按钮。还需要分别处理ajax和非ajax方式。


0
投票

此代码不起作用并且 add_action('woocommerce_add_to_cart', 'conversion_add_to_cart_event', 10, 4);

脚本标签中没有返回任何Dataleyer。

© www.soinside.com 2019 - 2024. All rights reserved.