Halloween Sale 15% off Ends in See the plans
PHP

GA4 view_item and add_to_cart Events for WooCommerce

Sends GA4 ecommerce events when a shopper views a product page and when they add a product to the cart, from the product page or with AJAX buttons on shop pages.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'wp_footer', function () {
    if ( ! function_exists( 'is_product' ) ) {
        return;
    }

    $currency = get_woocommerce_currency();
    $view     = null;

    if ( is_product() ) {
        $product = wc_get_product( get_queried_object_id() );

        if ( $product ) {
            $view = array(
                'currency' => $currency,
                'value'    => round( (float) wc_get_price_to_display( $product ), 2 ),
                'items'    => array(
                    array(
                        'item_id'   => $product->get_sku() ? $product->get_sku() : (string) $product->get_id(),
                        'item_name' => $product->get_name(),
                        'price'     => round( (float) wc_get_price_to_display( $product ), 2 ),
                    ),
                ),
            );
        }
    }
    ?>
<script>
(function () {
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    var currency = <?php echo wp_json_encode( $currency ); ?>;
    var view = <?php echo wp_json_encode( $view ); ?>;
    if (view) {
        gtag('event', 'view_item', view);
        var form = document.querySelector('form.cart');
        if (form) {
            form.addEventListener('submit', function () {
                var qty = parseInt((form.querySelector('input.qty') || {}).value, 10) || 1;
                var item = Object.assign({}, view.items[0], { quantity: qty });
                gtag('event', 'add_to_cart', { currency: currency, value: item.price * qty, items: [item] });
            });
        }
    }
    if (window.jQuery) {
        jQuery(document.body).on('added_to_cart', function (e, fragments, hash, button) {
            if (!button || !button.length) { return; }
            var b = button[0];
            gtag('event', 'add_to_cart', { currency: currency, items: [{ item_id: b.getAttribute('data-product_sku') || b.getAttribute('data-product_id'), item_name: b.getAttribute('aria-label') || '', quantity: parseInt(b.getAttribute('data-quantity'), 10) || 1 }] });
        });
    }
})();
</script>
    <?php
} );

Notes

Needs the GA4 tag (gtag.js) on the page. Prices are sent as displayed (including or excluding tax per your store settings).

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.