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.
Opens WPIDE on
Code
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 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.