Google Analytics 4 purchase event
Sends a GA4 “purchase” event with the order’s items and total from the order confirmation page, once per order. Needs the Google Analytics 4 snippet (or gtag.js) on the site.
<?php
add_action(
'woocommerce_thankyou',
static function ( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order || $order->get_meta( '_snipfire_ga4_sent' ) ) {
return;
}
$items = array();
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
$items[] = array(
'item_id' => $product ? ( $product->get_sku() ? $product->get_sku() : (string) $product->get_id() ) : '',
'item_name' => $item->get_name(),
'quantity' => $item->get_quantity(),
'price' => round( (float) $order->get_item_total( $item, false ), 2 ),
);
}
$data = array(
'transaction_id' => $order->get_order_number(),
'value' => round( (float) $order->get_total() - (float) $order->get_total_tax() - (float) $order->get_shipping_total(), 2 ),
'tax' => round( (float) $order->get_total_tax(), 2 ),
'shipping' => round( (float) $order->get_shipping_total(), 2 ),
'currency' => $order->get_currency(),
'items' => $items,
);
$order->update_meta_data( '_snipfire_ga4_sent', 1 );
$order->save();
echo '<script>window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push( arguments ); } gtag( "event", "purchase", ' . wp_json_encode( $data, JSON_HEX_TAG ) . ' );</script>';
}
);
Good to know
The same order is only sent once, even if the customer reloads the page. In the EU, the GA4 tag itself must respect consent (Consent Mode or your banner).
In these packs
- WooCommerce: account, emails and admin: A leaner My account page, handier order lists and emails, and lighter pages.
- More tracking codes: Google Ads, TikTok, LinkedIn, Pinterest, Hotjar, Plausible, site verification and a GA4 purchase event.