Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save celticwebdesign/7bea9890bdb075afc81aaf4e7aa0c381 to your computer and use it in GitHub Desktop.
Save celticwebdesign/7bea9890bdb075afc81aaf4e7aa0c381 to your computer and use it in GitHub Desktop.
Add Woocommerce products tracking code before main Google Analytics code in header.php
header.php
<?php
if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) {
// echo $wp->query_vars['order-received'];
// Lets grab the order
$order = wc_get_order( $wp->query_vars['order-received'] );
/**
* Put your tracking code here
* You can get the order total etc e.g. $order->get_total();
*/
$transactionId = $order->post->post_password;
$orderTotal = $order->get_total();
// This is how to grab line items from the order
$line_items = $order->get_items();
echo "
<script>
window.dataLayer = window.dataLayer || []
dataLayer.push({";
echo "
'transactionId': 'wc_".$transactionId."',
'transactionAffiliation': '',
'transactionTotal': '".$orderTotal."',
'transactionTax': '',
'transactionShipping': '',
'transactionProducts': [";
// This loops over line items
foreach ( $line_items as $item ) {
// This will be a product
$product = $order->get_product_from_item( $item );
// This is the products SKU
$item_sku = $product->get_sku();
$item_qty = $item['qty'];
$item_total = $order->get_line_total( $item, true, true );
$item_title = $product->post->post_title;
echo "
{
'name': '".$item_title."',
'sku': '".$item_sku."',
'category': '',
'price': ".$item_total.",
'quantity': ".$item_qty.",
},
";
}
echo "]
});";
echo "
</script>
";
}
?>
<!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXX');</script>
<!-- End Google Tag Manager -->
</head>
<body <?php body_class(); ?>>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment