# WooCommerce Purchase Data in the GTM dataLayer

> Pushes a GA4-style "purchase" ecommerce object to the Google Tag Manager dataLayer on the order received page, ready for GA4, Google Ads or Meta tags in GTM.

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

## Code

```php
add_action( 'woocommerce_thankyou', function ( $order_id ) {
    $order = wc_get_order( $order_id );

    if ( ! $order || $order->get_meta( '_wpide_gtm_purchase_sent' ) ) {
        return;
    }

    $items = array();

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        $cats    = $product ? wc_get_product_terms( $product->get_parent_id() ? $product->get_parent_id() : $product->get_id(), 'product_cat', array( 'fields' => 'names' ) ) : array();
        $items[] = array(
            'item_id'       => $product && $product->get_sku() ? $product->get_sku() : (string) $item->get_product_id(),
            'item_name'     => $item->get_name(),
            'item_category' => $cats ? $cats[0] : '',
            'price'         => round( (float) $order->get_item_total( $item, false ), 2 ),
            'quantity'      => (int) $item->get_quantity(),
        );
    }

    $push = array(
        'event'     => 'purchase',
        'ecommerce' => 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 || []; window.dataLayer.push({ ecommerce: null }); window.dataLayer.push(" . wp_json_encode( $push ) . ");</script>\n";

    $order->update_meta_data( '_wpide_gtm_purchase_sent', time() );
    $order->save();
}, 20 );
```

## Notes

Needs your GTM container on the page; create a Custom Event trigger for "purchase" in GTM. Sent once per order.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "WooCommerce Purchase Data in the GTM dataLayer" 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/
