Wednesday 23 February 2022

Cannot add google ads event to woocoommerce_add_to_cart hook

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?



from Cannot add google ads event to woocoommerce_add_to_cart hook

No comments:

Post a Comment