add_action( 'woocommerce_thankyou', 'push_purchase_datalayer', 10, 1 );
function push_purchase_datalayer( $order_id ) {
if ( ! $order_id ) return;
$order = wc_get_order( $order_id );
$items = array();
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
$items[] = array(
'id' => $product ? $product->get_id() : '',
'name' => $item->get_name(),
'price' => (float) $item->get_subtotal() / max( 1, $item->get_quantity() ),
'quantity' => $item->get_quantity(),
);
}
$data = array(
'event' => 'purchase',
'transactionId' => (string) $order->get_id(),
'transactionTotal' => (float) $order->get_total(),
'transactionTax' => (float) $order->get_total_tax(),
'currency' => get_woocommerce_currency(),
'coupon' => implode( ',', $order->get_coupon_codes() ),
'transactionProducts' => $items,
);
if ( ! $order->get_meta( '_gtm_purchase_fired' ) ) {
?>
update_meta_data( '_gtm_purchase_fired', true );
$order->save();
}
}