While it should be a few minutes job, it took me more than 10 hours trying to figure out why the following snippet is working but not as expected, although the site doesn’t use ajax for add_to_cart events.
For a very wierd reason the page refreshes when the code is active. I realize this because the log in the console(added_to_cart) disappears after a few moments of loading.
The wierd thing is that it has nothing to do with the hook that i’m using(although i also tried woocommerce_add_to_cart_validation with the exact same results) because if i leave only the console.log message it doesn’t have the same behavior. It’s like the gtag script is forcing a page reload.
Normally this shouldn’t be an issue because the event is actually sent to google ads, however there are other scripts that should run afterwards which do not(such as google analytics and others).
add_action( 'woocommerce_add_to_cart', 'custom_add_to_cart', 10, 2 );
function custom_add_to_cart( $cart_item_key, $product_id ) {
$_product = wc_get_product($product_id);
$price = $_product->get_price();
$current_url = home_url( $_SERVER['REQUEST_URI'] );
?>
console.log('added_to_cart');
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo ADS_ID ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?php echo ADS_ID ?>');
</script>
<script type="text/javascript">
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': '<? echo ADS_ADD_TO_CART; ?>',
'value': <?php echo $price ?>,
'currency': 'EUR',
'event_callback': callback
});
return false;
}
gtag_report_conversion('<?php echo $current_url; ?>');
</script>
<?php
}
any ideas?
2
Answers
I managed to figure out what's happening and i don't know how i missed it. here it is in case I had to change from:
to:
so it would stop the redirection
Your code does not work because the woocommerce_add_to_cart fires on the backend, and you’re trying to render the JavaScript code where it can not be executed.
If you want to catch the add-to-cart event, use WooCommerce JavaScript events or use good old addEventListener() on your add-to-cart buttons.