2016-10-20 37 views
-1

这是我的数组类似:如何在创建对象/数组的同时推送事件?

它不是在谷歌代码管理工具被认可。我被告知我需要与这些价值观同时推出一个活动。但是如何?

我已经尝试了一切!

这是我的代码:

<script> 

<?php 
    global $woocommerce; 
    $items = $woocommerce->cart->get_cart(); 
    $dataLayer = []; 
    foreach($items as $item => $values) { 
     $_product = $values['data']->post; 
?> 

<?php 
     $dataLayer[] = [ 
    'itemUnitID' => $_product->ID, 
       'itemUnitPrice' => get_post_meta($values['product_id'] , '_price', true), 
       'itemQuantity' => $values[quantity] 


     ]; 

    }; 

?> 
window.dataLayer = window.dataLayer || []; 
window.dataLayer.push(<?php echo json_encode($dataLayer); ?>); 

</script> 

理想的情况下,这就是我想我的数据层的样子:

enter image description here

+0

我投票,因为它是相同的,你问一个问题,http://stackoverflow.com关闭此问题后, /问题/ 40137320/GTM-犯规 - 认识 - 我 - 数据层,但是,控制台一样。你应该坚持编辑原始问题而不是发布一个新问题。 – nyuen

回答

0

你可以开始直接创建您在需要什么结束。

<?php 
    //Init the array with default data. 
    $dataLayer = [ 
    'checkout' => 'overview', 
    'customer' => [], //I don't know what you will have here 
    'product' => [], //At first we create an empty array and we will add here the products. 
    ] 

    global $woocommerce; 
    $items = $woocommerce->cart->get_cart(); 
    //Get all products and go one by one. 
    foreach($items as $item => $values) { 
     $_product = $values['data']->post; 
     //We will add a new product in $dataLayer product sub array 
     $dataLayer['product'][] = [ 
       'sku' => $_product->ID, 
       'unit_price' => get_post_meta($values['product_id'] , '_price', true), 
       'quantity' => $values[quantity], 
       'category' => $values[category], //Or how you can get the category name for a product. 
       'name' => $values[name], //Or how you can get the name of a product 
       'parent_id' => $values[parent_id], //or how you can get the parent_id of a product. 

     ]; 

    }; 

?> 

js该组数据层与json_encode值从php

<script> 
     window.dataLayer = <?php echo json_encode($dataLayer); ?>; 
</script>