问题
So right now I am doing something like what is below. What I want to be able to do is pass data dynamically to GTM.. I know I am doing it wrong but I need some help in figuring out how i need to go about this. Again. ALL I want to do is send some data in PHP variables to Google Tag Manager so I can view in GA.
Thank you!
<script>
dataLayer.push({
'transactionId': '<?php echo $order['id']; ?>',
'transactionTotal': '<?php echo number_format($order['subtotal'],2) ?>',
'transactionProducts': [{
'sku': '',
'name': '<?php echo $order['programName']; ?>',
'price': ,
'quantity':
}],
'event' : 'OrderComplete'
});
</script>
回答1:
It seems that you just missed the ' on your json object.
dataLayer.push({
'transactionId': '<?php echo $order['id']; ?>',
'transactionTotal': '<?php echo number_format($order['subtotal'],2) ?>',
'transactionProducts': [{
'sku': '',
'name': '<?php echo $order['programName']; ?>',
'price': 'here',
'quantity': 'here'
}],
'event' : 'OrderComplete'
});
The rest is fine.
If you got no values for those field, let them be empty by writing an empty string ''.
<?php
function myProducts() {
$result = array();
foreach($products as $product) {
array_push($result, "{
'sku': '" . $product['sku'] . "',
'name': '" . $product['name'] . "',
'price': '" . $product['price'] . "',
'quantity': '" . $product['quantity'] . "'
}");
};
return implode(",", $result);
}
?>
dataLayer.push({
'transactionId': '<?php echo $order['id']; ?>',
'transactionTotal': '<?php echo number_format($order['subtotal'],2) ?>',
'transactionProducts': [<?php echo myProducts()?>],
'event' : 'OrderComplete'
});
来源:https://stackoverflow.com/questions/39878853/use-php-in-script-to-send-data-too-google-tag-manager