I am looking for a way to track add to cart event in woocommerce, push the data on a few datalayers (product name, quantity, price and sku) so I can track them in google tag manager. We are pretty new on php and I cannot seem to find any example online. Could you suggest a solution please?
1条回答 默认 最新
- dongqi7631 2016-08-09 17:35关注
Alright, so I've come up with a couple of options.
Option #1
This is not a very clean approach, but should work without much trouble. The idea is to bind the
.single_add_to_cart_button
to perform an AJAX request so you can transfer all the visible data in the product page to a PHP array.Add this JS to the product page:
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 } }); });
Then, as server-side 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' );
Option #2
I prefer this idea, but I haven't fully tested it. You'll be using the
woocommerce_add_cart_item
filter, with something like the following in 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 );
解决 无用评论 打赏 举报
悬赏问题
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号
- ¥15 基于单片机的靶位控制系统
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度