# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Analytics & Tracking](https://wpide.com/library/category/analytics/)
- Requires: WooCommerce
- Tags: google-analytics, ga4, woocommerce, ecommerce
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/analytics-ga4-woo-purchase/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "GA4 Purchase Event for WooCommerce Orders" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
