PHP Variables in dataLayer

4.1k views Asked by At

I am new to PHP and dataLayer but I have the below code which includes a dataLayer with PHP code. I want to use the datalayer variables to map them to google tag manager and would like to use the PHP variables available in the below code. What I would like to populate from the PHP variables are as below.

Name, Price, Category and Quantity to get populated from the PHP variables to the data layer structure.

Also, it should get all the product variables similarly depending on how many are there on the page where this code is getting loaded.

Also, want the transactionTotal to be populated which is the sum of all the prices of the individual product prices.

var cartItemMap = new Object();
    var cartItem1 = null;
    var cartItem2 = null;
    var cartItem3 = null;
    var cartItem4 = null;
    var cartItem5 = null;
    var cartItem6 = null;
    var cartItem7 = null;
    var cartItem8 = null;
    var cartItem9 = null;
<?php
    $size = 0;
    foreach($_SESSION['product'] as $key => $pro){ 
        $size = $size + 1;
    }
    $i = 1;
    foreach($_SESSION['product'] as $key => $pro){ 

        if($size > 9){
            $size = $size -1;
        }
        else{
?>

dataLayer = [{
    'transactionId': Math.floor((Math.random() * 100) + 1),
    'transactionTotal': 11.99,
    'transactionTax': 1.29,
    'transactionShipping': 5,
    'transactionProducts': [{
        'sku': 121212,
        'name': "Test",
        'category': "Testing Category",
        'price': 33,
        'quantity': 1
    },{
        'sku': 'AA1243544',
        'name': 'Socks',
        'category': 'Apparel',
        'price': 9.99,
        'quantity': 2
    }]
}];

if("<?php echo $pro['product_name'] ?>" != ''){
    cartItem<?php echo $i ?> = new Object();

    cartItem<?php echo $i ?>.productName = "<?php echo $pro['product_name'] ?>";
    cartItem<?php echo $i ?>.productPrice = "<?php echo $pro['product_price'] ?>";
    cartItem<?php echo $i ?>.productQuantity = <?php echo $pro['product_quantity'] ?>;
    cartItem<?php echo $i ?>.productCategory = "<?php echo $pro['product_category'] ?>";
    cartItemMap[<?php echo $key ?>] = cartItem<?php echo $i ?>;
}
<?php
        $i = $i + 1;
    }
}
?>  

Help appreciated.

1

There are 1 answers

5
Sepultura On

you could try something like this:

<script type="text/javascript">
    var cartItems = [
        <?php foreach($_SESSION['product'] as $key => $pro): ?>
        {
            productName: "<?= $pro['product_name']; ?>",
            productPrice: "<?= $pro['product_price']; ?>",
            productQuantity: "<?= $pro['product_quantity']; ?>",
            productCategory: "<?= $pro['product_category']; ?>"
        },
        <?php endforeach; ?>
    ];
</script>

This creates an array (cartItems) of objects (cartItem)