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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.