Reputation: 169
I've been trying to figure out how to make a dataLayer for the Order Confirmation page (Thankyou.php). I wanted to add the following function (via functions.php or Code Snippet) but it gives a fatal error when I try. Can anyone see what I'm doing wrong or if there is a better way to do this?
I'm fairly new but trying to learn and I've been researching but can't find the answer, sorry if this may be a novice question. It gives a fatal error for the < in script so I thought maybe I wasn't supposed to have in PHP but when I remove that then I get a fatal error for unexpected { on same line:
add_action( 'woocommerce_thankyou', 'checkout_datalayer' );
function checkout_datalayer( $order_id ) {
<script>
dataLayer.push({
'ecommerce': {
'currencyCode': '<?php echo $order->get_order_currency(); ?>',
'purchase': {
'actionField':{
'id': '<?php echo $order->get_order_number(); ?>',
'affiliation': 'Website',
'revenue': <?php echo number_format($order->get_total(), 2, ".", ""); ?>,
'shipping': <?php echo number_format($order->calculate_shipping(), 2, ".", ""); ?>,
<?php if($order->get_used_coupons()): ?>
'coupon': '<?php echo implode("-", $order->get_used_coupons()); ?>'
<?php endif; ?>
},
'products': [
<?php
foreach($order->get_items() as $key => $item):
$product = $order->get_product_from_item( $item );
?>
{
'name': '<?php echo $item['name']; ?>',
'id': '<?php echo $product->get_sku(); ?>',
'price': '<?php echo number_format($order->get_line_subtotal($item), 2, ".", ""); ?>',
'brand': 'Brand',
'quantity': <?php echo $item['qty']; ?>
},
<?php endforeach; ?>
]
}
}
});
</script>
}
Upvotes: 0
Views: 1779
Reputation: 169
To anyone interested, I figured out the issue I believe. It was assuming the entire thing was PHP and the only way to stop that was to add ?>
before the <script>
and <?php
after the </script>
.
Upvotes: 3