Skip to content

Instantly share code, notes, and snippets.

@SearchStar
Last active May 9, 2021 23:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SearchStar/8df72c351199f5b573b1 to your computer and use it in GitHub Desktop.
Save SearchStar/8df72c351199f5b573b1 to your computer and use it in GitHub Desktop.
Implementing a Google Tag Manager ecommerce data layer with PHP
<?php
$transactionId='test1001';
$sku=array('test1003','test1001','test1002');
$name=array('six1','six2','six3');
$category=array('142139113','161477257','574557754');
$price=array(53.90,9.99,36.36);
$quantity=array(1.00,1.00,1.00);
$transactionAffiliation='affil';
$transactionTotal='100.25';
$transactionTax=00.00;
$transactionShipping='0.00';
$length = count($sku);
for ($i=0; $i+1<=$length; $i++)
{
if ($i+1<$length)
{
$cartProducts[$i] = "
{
'sku': '" . $sku[$i] . "',
'name': '" . $name[$i] . "',
'category': '" . $category[$i] . "',
'price': " . $price[$i] . ",
'quantity': " . $quantity[$i] . "
},"
;
}
else
{
$cartProducts[$i] = "
{
'sku': '" . $sku[$i] . "',
'name': '" . $name[$i] . "',
'category': '" . $category[$i] . "',
'price': " . $price[$i] . ",
'quantity': " . $quantity[$i] . "
}"
;
}
};
?>
<html>
<head>
<script>
dataLayer = [{
'transactionId': '<?php echo $transactionId?>',
'transactionAffiliation': '<?php echo $transactionAffiliation?>',
'transactionTotal': <?php echo $transactionTotal?>,
'transactionTax': <?php echo $transactionTax?>,
'transactionShipping': <?php echo $transactionShipping?>,
'transactionProducts': [<?php foreach ($cartProducts as $row) {echo $row;}?>]
}];
</script>
</head>
<body>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-####"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-####');</script>
<!-- End Google Tag Manager -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment