Will this work to track purchases through Google Tag Manager?

[ad_1]

Will this code snippet in the functions.php insert the JS tracking code onto the order confirmation page, so that I can track it with Google Tag Manager?

function send_purchase_data_to_gtm($order_id) {
// Get the order object
$order = wc_get_order($order_id);

// Check if the order exists
if (!$order) {
return;
}

// Get order data
$value = $order->get_total();
$currency = $order->get_currency();
$transaction_id = $order->get_order_number();
$items = [];

// Loop through the order items
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = [
‘item_id’ => $product->get_id(),
‘item_name’ => $product->get_name(),
‘quantity’ => $item->get_quantity(),
‘item_brand’ => ”, // Replace with the brand if available
‘item_category’ => ”, // Replace with the category if available
‘price’ => $product->get_price()
];
}
?>
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
‘event’: ‘purchase’,
‘value’: <?php echo json_encode($value); ?>,
‘currency’: <?php echo json_encode($currency); ?>,
‘transaction_id’: <?php echo json_encode($transaction_id); ?>,
‘items’: <?php echo json_encode($items); ?>
});
</script>
<?php
}
add_action(‘woocommerce_thankyou’, ‘send_purchase_data_to_gtm’);

[ad_2]

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer