Skip to content

Instantly share code, notes, and snippets.

@morvy
Created June 30, 2023 17:58
Show Gist options
  • Save morvy/921a5ace2a29221f41d17c107da6780d to your computer and use it in GitHub Desktop.
Save morvy/921a5ace2a29221f41d17c107da6780d to your computer and use it in GitHub Desktop.
Fix add_to_cart event not firing on Woo Product where theme uses custom ajax event
<?php
/**
* GA4 event: add_to_cart
*/
add_action('wp_footer', function() {
if (!is_product()) return;
?>
<script type="text/javascript">
// track add to cart events for products on product detail pages
jQuery(document).ready(function($) {
$(document).ajaxSuccess(function(event, xhr, settings) {
if ( xhr.status == 200 &&
xhr.responseText &&
xhr.responseText.indexOf('popup') !== -1 &&
settings.data &&
settings.data.indexOf( 'woocommerce_ajax_add_to_cart' ) !== -1
) {
let event_target_element = document.querySelector('.js-add-to-cart');
if ( !event_target_element ) {
// for some reason event target is not specificed
return true;
}
const product_form = event_target_element.closest( 'div.c-product-detail__actions' );
if ( !product_form ) {
return true;
}
const product_id_el = gtm4wp_use_sku_instead ? product_form.querySelector( '[name=gtm4wp_sku]' ) : product_form.querySelector( '[name=gtm4wp_id]' );
const product_data = {
'id': product_id_el && product_id_el.value,
'name': product_form.querySelector( '[name=gtm4wp_name]' ) && product_form.querySelector( '[name=gtm4wp_name]' ).value,
'price': product_form.querySelector( '[name=gtm4wp_price]' ) && product_form.querySelector( '[name=gtm4wp_price]' ).value,
'category': product_form.querySelector( '[name=gtm4wp_category]' ) && product_form.querySelector( '[name=gtm4wp_category]' ).value,
'quantity': product_form.querySelector( '[name=quantity]' ) && product_form.querySelector( '[name=quantity]' ).value,
'stocklevel': product_form.querySelector( '[name=gtm4wp_stocklevel]' ) && product_form.querySelector( '[name=gtm4wp_stocklevel]' ).value,
'brand': product_form.querySelector( '[name=gtm4wp_brand]' ) && product_form.querySelector( '[name=gtm4wp_brand]' ).value
};
// fire ga4 version
window[ gtm4wp_datalayer_name ].push({
'event': 'add_to_cart',
'ecommerce': {
'currency': gtm4wp_currency,
'value': product_data.price * product_data.quantity,
'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
}
});
}
});
});
</script>
<?php
}, 20, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment