function add_datalayer_script() {
if (is_order_received_page()) {
global $wp;
// Get the order ID from the URL
$order_id = apply_filters('woocommerce_thankyou_order_id', absint($wp->query_vars['order-received']));
if (!$order_id) {
return;
}
// Get the order object
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// Prepare order data
$order_data = [
'order_id' => $order->get_id(),
'order_total' => $order->get_total(),
'currency' => $order->get_currency(),
'products' => []
];
// Loop through order items
foreach ($order->get_items() as $item) {
$product = $item->get_product();
if (!$product) {
continue;
}
$order_data['products'][] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => $product->get_price(),
'quantity' => $item->get_quantity()
];
}
// Output the data layer script
?>
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'purchase',
'order': <?php echo json_encode($order_data); ?>
});
</script>
<?php
}
}
add_action(‘wp_footer’, ‘add_datalayer_script’);
I added this custom code and it started
But we need the plugin to add this automatically