Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

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.

  • Type PHP
  • Runs Everywhere (runs as WordPress loads)
  • Needs WooCommerce
  • Category WooCommerce
  • Tested with WordPress 7.1, WooCommerce 11.1
PHP
<?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

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.