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?
Alright, so I've come up with a couple of options.
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' );
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.