Google Tag Tracking for WooCommerce Purchases

WooCommerce does not include a thank you page which makes it a little more challenging to embed tracking events for things like Google Tag Manager and AdWords.  

The code snippet below will allow you to track orders in Google along with the order ID and Order Total. This snippet should be placed in your WordPress theme’s functions.php file with the “XX-XXXXXXXXX” and the “ZZZZZZZZZZ” replaced with your own unique values from Google. Proper file backups and developer experience is recommended to make this change. Please contact Valice WordPress support for assistance if you do not feel comfortable making this change.

add_action('woocommerce_thankyou','add_purchase_conversion_tracking');

function add_purchase_conversion_tracking($order_id) {
if (!$order_id) return;

$order = wc_get_order($order_id);if ($order) {
$order_total = $order->get_total(); ?>
<!-- Global site tag (gtag.js) - Google Ads: XXXXXXX -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XX-XXXXXXXXX"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XX-XXXXXXXXX');
</script>

<!-- Event snippet for Product Purchase conversion page --> <script>gtag('event', 'conversion', {
'send_to': 'XX-XXXXXXXXXX/ZZZZZZZZZZZZ',
'value': '<?= $order_total ?>',
'currency': 'USD',
'transaction_id': ''});
</script>
<?php
}
}