GA4 Purchase Event for WooCommerce Orders
Sends a Google Analytics 4 "purchase" event with the order ID, value, tax, shipping and items when a customer reaches the order received page, once per order.
Opens WPIDE on
Code
add_action( 'woocommerce_thankyou', function ( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order || $order->get_meta( '_wpide_ga4_purchase_sent' ) ) {
return;
}
$items = array();
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
$qty = max( 1, (int) $item->get_quantity() );
$items[] = array(
'item_id' => $product && $product->get_sku() ? $product->get_sku() : (string) $item->get_product_id(),
'item_name' => $item->get_name(),
'price' => round( (float) $order->get_item_total( $item, false ), 2 ),
'quantity' => $qty,
);
}
$data = array(
'transaction_id' => (string) $order->get_order_number(),
'value' => round( (float) $order->get_total(), 2 ),
'tax' => round( (float) $order->get_total_tax(), 2 ),
'shipping' => round( (float) $order->get_shipping_total(), 2 ),
'currency' => $order->get_currency(),
'coupon' => implode( ',', $order->get_coupon_codes() ),
'items' => $items,
);
echo "<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('event', 'purchase', " . wp_json_encode( $data ) . ");</script>\n";
$order->update_meta_data( '_wpide_ga4_purchase_sent', time() );
$order->save();
}, 20 );
Notes
Needs the GA4 tag (gtag.js) on the page, for example from the Google Analytics 4 snippet. Reloading the thank-you page does not send the event again.
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.