add_action( ‘woocommerce_before_checkout_form’, ‘push_transaction_data_to_gtm_on_checkout’ );
function push_transaction_data_to_gtm_on_checkout() {
global $woocommerce;
// Get the cart object
$cart = $woocommerce->cart;
// Get the products in the cart
$products = array();
foreach ( $cart->get_cart() as $item ) {
$product = wc_get_product( $item[‘product_id’] );
$products[] = array(
‘name’ => $product->get_name(),
‘id’ => $product->get_id(),
‘price’ => $product->get_price(),
‘quantity’ => $item[‘quantity’],
);
}
// Get the cart total
$total = $cart->total;
// Get the tax total
$tax = $cart->tax_total;
// Get the shipping total
$shipping = $cart->shipping_total;
// Get the currency
$currency = get_woocommerce_currency();
?>
<script>
dataLayer.push({
‘event’: ‘transactionData’,
‘ecommerce’: {
‘checkout’: {
‘actionField’: {
‘revenue’: ‘<?php echo $total; ?>’,
‘tax’: ‘<?php echo $tax; ?>’,
‘shipping’: ‘<?php echo $shipping; ?>’,
‘currency’: ‘<?php echo $currency; ?>’
},
‘products’: <?php echo json_encode( $products ); ?>
}
}
});
</script>
<?php
}
add_action( ‘woocommerce_thankyou’, ‘push_transaction_data_to_gtm_on_thankyou’, 10, 1 );
function push_transaction_data_to_gtm_on_thankyou( $order_id ) {
// Get the order object
$order = wc_get_order( $order_id );
// Get the products in the order
$products = array();
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
$products[] = array(
‘name’ => $product->get_name(),
‘id’ => $product->get_id(),
‘price’ => $product->get_price(),
‘quantity’ => $item->get_quantity(),
);
}
// Get the order total
$total = $order->get_total();
// Get the tax total
$tax = $order->get_total_tax();
// Get the shipping total
$shipping = $order->get_shipping_total();
// Get the order number
$order_number = $order->get_order_number();
// Get the currency
$currency = $order->get_currency();
// Push the transaction data to the data layer
?>
<script>
dataLayer.push({
‘event’: ‘transactionData’,
‘ecommerce’: {
‘purchase’: {
‘actionField’: {
‘id’: ‘<?php echo $order_number; ?>’,
‘revenue’: ‘<?php echo $total; ?>’,
‘tax’: ‘<?php echo $tax; ?>’,
‘shipping’: ‘<?php echo $shipping; ?>’,
‘currency’: ‘<?php echo $currency; ?>’
},
‘products’: <?php echo json_encode( $products ); ?>
}
}
});
</script>
<?php
}
source https://developers.google.com/analytics/devguides/collection/ua/gtm/enhanced-ecommerce