Track Add to Cart events in WooCommerce with this Google Tag Manager code snippet

Track Add to Cart events in WooCommerce with this Google Tag Manager code snippet
Photo by Kenrick Baksh / Unsplash

This article provides a code snippet that sends an add to cart conversion event to Google Analytics when a customer clicks the add to cart button on a WooCommerce website. The code is easy to implement and helps track important e-commerce metrics to improve sales. Feel free to modify the code for other events too 👍

Note: This snippet takes care of both - ajax and non-ajax add to cart events 💡

The code

To implement this code, simply add it to the functions.php file of your WooCommerce theme. The code consists of three parts:

Note: The code is explained below the snippet

Part 1: Hook event tracking to standard, non-ajax add to cart action

If you have enabled the Ajax events from your WooCommerce settings, you need to handle the event in two different ways: Ajax and non-ajax.

When the woocommerce_add_to_cart event is triggered, the conversion_add_to_cart_event function is called and checks if the request has been made by Ajax or by the basic HTTP request.

 * Add add_to_cart event to add to cart action. 
 * This only applies to events not triggered by ajax.
add_action('woocommerce_add_to_cart', 'conversion_add_to_cart_event', 10, 4);
function conversion_add_to_cart_event($cart_id, $product_id, $request_quantity, $variation_id)
	// If ajax request, return early.
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // ...

Other than this, the rest is pretty basic.

To make the tracking event as rich as possible, product data must be appended to the add to cart link button. This button is the button that adds the product to the cart when you are not looking at the product page, but rather at a product list (such as a category or a list of recent products). The necessary data is appended as data-attributes.

 * include product data info to add_to_cart button
add_filter('woocommerce_loop_add_to_cart_link', 'conversion_add_to_cart_button', 10, 2);

 * Add product data to the add to cart button as data attributes.
 * @param $element (string) the button element
 * @param $product (object) the product object
 * @return string $element the button element with data attributes
function conversion_add_to_cart_button($element, $product)
	try {
		// Add product data to the button as data attributes
		$attributesToAdd = array(
			'data-product-id' => $product->get_id(),
			'data-product-price' => $product->get_price(),
			'data-product-regular-price' => $product->get_regular_price(),
			'data-product-sale-price' => $product->get_sale_price(),
			'data-product-variation-id' => $product->get_id(),
			'data-product-variation-price' => $product->get_price(),
			'data-product-variation-regular-price' => $product->get_regular_price(),
			'data-product-variation-sale-price' => $product->get_sale_price(),
			'data-product-variation-name' => $product->get_name(),
			'data-product-variation-category' => join(",", wp_get_post_terms($product->get_id(), 'product_cat', array("fields" => "names"))),

		foreach ($attributesToAdd as $key => $value) {
			$element = str_replace('>', ' ' . $key . '="' . $value . '">', $element);
	} catch (Exception $e) {
		// Do nothing if there is an error.

	return $element;

Part 3: Embed the JavaScript event listener to the document

To add the added_to_cart event listener script to the document, hook into the wp_footer action. The script gathers the necessary data, formats the object, and sends the event.

 * Add to cart event when adding to cart via ajax using jquery hooked into wp_footer.
add_action('wp_footer', 'conversion_add_to_cart_event_ajax');
function conversion_add_to_cart_event_ajax()
	jQuery(document).on('added_to_cart', function(e, f, cart_hash, button) {
		try {
            // Format the data to match the add_to_cart event.
            var items = {
                'item_variant': 'default',
                'quantity': 1,
                'discount':'product-sale-price') ?'product-regular-price') -'product-sale-price') : 0,

            // If product has categories, add them to the item array. Max 5 categories.
            var categories ='product-variation-category').split(',');
            for (var i = 0; i < 5; i++) {
                if (categories[i] == undefined) {
                if (i == 0) {
                    items['item_category'] = categories[i];
                } else {
                    items['item_category' + (i + 1)] = categories[i];
            // call the add_to_cart event.
            gtag('event', 'add_to_cart', {
                'currency': 'EUR',
                'items': [items]
        } catch (e) {
            // Log error to console as a warning.

And that's it! With these simple steps, you have set up the event tracking for the add_to_cart event on your WooCommerce website. Happy tracking!

Privacy Policy