I found this question mentioned that the custom dimension value must set before ga('send', 'pageview');
But what if I use Google Tag Manager?
dataLayer.push({
'postId': '{{ $post->id }}',
'userId': '{{ auth()->user()->id }}',
});
I've set up the data layer variable to GTM to trigger GA. But when I look at the GA report, and filter by custom dimension, it's not working.
I checked with the debug, Tags Fired On This Event shows below
How do I set the custom dimension before it sent to GA pageview?
You would need to define the datalayer BEFORE loading of the GTM script.
Example to place at the top of the page before GTM is loaded:
<script>
dataLayer = [{
'postId': '{{ $post->id }}',
'userId': '{{ auth()->user()->id }}',
}];
</script>
When you do this, the data is available right away.
Another thing you can do is instead of using the datalayer, if the pages are rendered server-side, is to use tags with the postid and userid as values. This will ensure they're loaded before GTM.
https://developers.google.com/tag-manager/devguide#adding-data-layer-variables-to-a-page
Related
I am looking for a way to pass transaction data up from a LWC (lightning web component) to GA and not start a new session.
The primary issue is that the helper on the custom lighting web component is firing correctly, however when the ga(ecommerce, send) fires from within the LWC, it is setting a different clientID in the browswer.
If i try using ga(function(tracker) {var clientId = tracker.get('clientId');}); in the LWC it errors out as clientId is undefined.
I would like to be able to use the clientId instead of autolinker when calling
ga('create', trackingId, 'auto', { allowLinker: true });
ga('require', 'linker');
ga('require', 'ecommerce');
ga('linker:autoLink', [$A.get("$Label.c.Community_Site_URL")]);
there's two pushes going out. One is grand total via datalayer, the other is via ga add transaction
datalayer push
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'transactionId ': order.Id,
'transactionAffiliation': order.SalesStore.Name,
'transactionTotal ': order.GrandTotalAmount,
'transactionShipping': order.TotalAdjustedDeliveryAmount,
'transactionTax': order.TotalTaxAmount
});
GA Add transaction
ga('ecommerce:addTransaction', {
'id': order.Id,
'affiliation': order.SalesStore.Name,
'revenue': order.GrandTotalAmount,
'shipping': order.TotalAdjustedDeliveryAmount,
'tax': order.TotalTaxAmount
});
orderItems.forEach(item => {
ga('ecommerce:addItem', {
'id': order.Id,
'name': item.orderItemInstance.zzzz.Name,
'sku': item.orderItemInstance.zzzz.StockKeepingUnit,
'price': item.orderItemInstance.TotalPrice,
'quantity': item.orderItemInstance.Quantity
});
});
ga('ecommerce:send');
This successfully fires to GA, and we can see the transactions. However, using the chrome extension, I can see that a new session has started for just the transaction event. So, for the main user session it will show the user visiting checkout and then order complete page, but no transaction info, while we see single page sessions for the transactions (and no campaign or adwords association).
is it possible to pass a value from the main window clientId to the LWC? that should allow us to link to the same session
Another solution mentioned passing data from the LWC to Aura. However, we already have the data going to GA. ("Whatever data you want to send to Google Analytics, send it from LWC to Aura through an event. And From Aura Component, fire a Google analytics event along with data received from LWC.") https://salesforce.stackexchange.com/questions/299303/google-analytics-event-tracking-in-community-using-lwc
this is a different use case as I just want the clientId and session to match
is there a GTM solution that will allow us to post to the main datalayer as opposed to how the datalayer push is working now?
In a symfony e-commerce project, to create a product view frequency report such that view count is increased when the user navigate to /product/detail/{id}. I am using Google Tag Manager and Analytics using the following as reference:
https://support.usabilla.com/hc/en-us/articles/360015738812-Integration-with-Google-Analytics-using-GTM-Data-Layer#
Google Tag Manager Setting
1. Create trigger
Trigger Type: Page View
Trigger Fire On: Some Page Views (Page path : contains : /products/detail)
2. Create variables
Name: dlv - productName
Variable Type: Data Layer Variable
Name: product.productName
Create Tag
Tag Type: Google Analytics: Universal Analytics
Track Type: Event
Category: Product Detail // static text
Action: View {{dlv - productName }}
Label: {{ dlv - productName }}
Value: {{ dlv - productName }}
Google Analytics Settings: {{ Google_Analytics_Track_ID_Settings }}
Tiggering: {{ Trigger_created_in_step_1 }}
Product Page
<script>
dataLayer.push({
'product': {
'productId': {{ Product.id }},
'productName': '{{ Product.name }}'
}
});
</script>
I can see dataLayer array is being sent to Google Tag Manager in the debug window. In Google Analytics > Behavior > Events > Top Events, I can see Product Detail in Event Category column. When I click the link the Event Action only shows View and Event Label is (not set). I want to create a tabular report like Product Detail: View Orange: 3, Product detail: View Apple: 4.
Cross-check that your {{ dlv - productName }} variable is properly populated and the value is available to the tag at the moment tag fires. If its value is populated later then the tag fires your event action would be tracked as (not set). If this is the case consider changing your trigger type to Window loaded or other event so the tag would grab the proper value from DL.
Although the key concept is provided in earlier answer, there are other solutions as well, which might give you better results.
So basically, you need to ensure, that the data you want to use from the dataLayer is available, when your tag is launched.
To achieve this, you can delay the tag to Window Loaded event, but you should be aware, that based on the size and content type of your page, a given percentage of your users will not have Window Loaded trigger launched, so you could miss part of your data. (They close the browser, navigate to other page before Window Loaded is reached.)
So an other option is to have the data pushed into the dataLayer before GTM is initialized. So your code looked something like this, placed above main GTM code in <head>:
<script>
var dataLayer = window.dataLayer || []; //define dataLayer, while avoiding overwriting its content
dataLayer.push({
'product': {
'productId': {{ Product.id }},
'productName': '{{ Product.name }}'
}
});
</script>
This way, your page view event will already see this data.
An other option would be to leave your code at it's current place, but to specify a triggering event, to let GTM know about the new data:
<script>
dataLayer.push({
'event': 'productDataReady',
'product': {
'productId': {{ Product.id }},
'productName': '{{ Product.name }}'
}
});
</script>
This way, you need to modify the trigger of your tag to be a Custom Event, matching the string used in the event variable. In this case, the data is available at this specific event.
Also, please note, that {{ dlv - productName }} should probably not used as event value, as Google Analytics accepts only integer values, while product name is likely to be a string.
An other consideration, is that you haven't specified (or at least haven't included it in your post), that the event should be non-interaction. If you generate an interactive event with your page load, assuming you also fire a pageview hit, you'll get an extremely low bounce rate.
I'm trying to set up ecommerce tracking using Google Tag Manager however I cannot get the data to appear within google analytics?
Use such code in header.tpl
{if isset($page_name) && $page_name|escape:'html':'UTF-8' == "order-confirmation"}
<script type="text/javascript">
window.dataLayer = window.dataLayer || []
dataLayer.push({ldelim}
'transactionId': '{$id_order}',
'transactionTotal': {$total_paid_tax_incl},
'transactionProducts': [
{foreach from=$products item=product}
{ldelim}
// List of productFieldObjects.
'sku': '{$product.id}',
'name': '{$product.name}', // Name or ID is required.
//'category': '{$product.X}',
'price': {$product.price},
'quantity': 1 // Optional fields may be omitted or set to empty string.
{rdelim}
{if !$smarty.foreach.product.last},{/if}
{/foreach}
]
{rdelim});
</script>
{/if}
But nothing works
Your datalayer declaration needs to be above the GTM snippet.
Also the noscript part of GTM should be immediately after .
I think you should look through the documentation incase you have other implementation issues:
How to install GTM: https://support.google.com/tagmanager/answer/6103696?hl=en&ref_topic=3441530
Ecommerce with GTM: https://support.google.com/tagmanager/answer/6107169?hl=en
I want to use GTM to track eCommerce transactions. This is a test for client environments where the code might be placed after the GTM code snippet which is why using Dom Ready as a trigger for the transaction tag is not reliable.
This is my test code:
<body>
<!-- Google Tag Manager -->
<script>window.dataLayer = window.dataLayer || [];</script>
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-M4RNT2"
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-XXXXXX');</script>
<!-- End Google Tag Manager -->
<div class="container">
<script>
window.dataLayer = window.dataLayer || []
dataLayer.push({
'transactionId': '32698',
'transactionAffiliation': 'Acme Clothing',
'transactionTotal': 38.26,
'transactionTax': 1.29,
'transactionShipping': 5,
'transactionProducts': [{
'sku': 'DD44',
'name': 'T-Shirt',
'category': 'Apparel',
'price': 11.99,
'quantity': 1
},{
'sku': 'AA1243544',
'name': 'Socks',
'category': 'Apparel',
'price': 9.99,
'quantity': 2
}]
});
</script>
</body>
As you can see the eCommerce code is taken straight from the Google documentation here.
I made sure that the pageview tag I'm firing works and I can see myself on the realtime view.
The issue is that no matter what I do to trigger the transaction tag, no eCommerce transactions are shown in Google Analytics.
Here is what I've tried:
Using 'event': 'eCommerce' right after the transaction products or in a separate script tag after the transaction code push and then using that event as a trigger
I've created a dataLayer variable in GTM that references transactionId and defaults it to false and then using event gtm.dom as a trigger with a filter for transactionId does not equal false
The frustrating part is that I have the GTM preview window open and it looks perfectly like it should work.
In attempt 1 above it shows a sequence of pageview, message, eCommerce DOM ready, page load where the dataLayer after message is correctly filled with transaction data and the eCommerce tag firing on the eCommerce event (i.e. data is in the dataLayer for sure.
In attempt 2 the dataLayer after Message is filled with transaction data and the eCommerce tag is fired on the DOM Ready event.
This has been going on for days now so it isn't a case of "the data hasn't shown up in GA yet". I am using the right UA tag since both tags reference the sasme onstant GTM variable and since I see myself in realtime the pageview tag uses the right UA and therefore so does the transaction tag. And yes eCommerce is obviously enabled in the view settings.
Simply pushing the transaction data to the data layer will not trigger the tracking to work. You need an action such as a pageview to pick up the transaction data and send it.
If you are unable to add the data layer before the GTM snippet, my recommendation would be the following:
Convert your code to be in the Enhanced Ecommerce format (provided below)
Add a custom event, in this case it is named trackTrans.
Add an event tag in GTM, labeled similar to Send Transaction. You can specify whatever values you'd like the for the event category/action/label.
In the event tag go to more settings > Ecommerce Features, enable Enable Enhanced Ecommerce Feature and Use data layer
Setting the trigger to be a Custom Event and specify trackTrans for the value
In your view settings make sure to enbable enhanced ecommerce tracking
dataLayer.push({
'ecommerce': {
'purchase': {
'actionField': {
'id': 'T12345', // Transaction ID. Required for purchases and refunds.
'affiliation': 'Online Store',
'revenue': '35.43', // Total transaction value (incl. tax and shipping)
'tax':'4.90',
'shipping': '5.99',
'coupon': 'SUMMER_SALE'
},
'products': [{ // List of productFieldObjects.
'name': 'Triblend Android T-Shirt', // Name or ID is required.
'id': '12345',
'price': '15.25',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Gray',
'quantity': 1,
'coupon': ''
}]
}
},
'event' : 'trackTrans'
});
With what I have described above, the page will load then an event will fire and send the ecommerce transaction data with it.
As per your reference to the Google documentation, you need to
Place this code above the Google Tag Manager container snippet so that the data layer is ready when Google Tag Manager fires the Google Analytics tag asynchronously.
I have found a way to make it work. Ryan's answer was close but our experience with using event based triggers was spotty at best. I am now using the following setup that essentially guarantees transaction pickups by GTM unless the code is dynamically injected after page load via JS.
Here is how:
I created a dataLayer Variable which references transactionId and set its default to false
I created a trigger of type Custom Event, set the event to gtm.dom and a filter for the dataLayer variable I created to be not equal to false.
This ensures an actual transaction on the page overwrites the default value of false in that GTM variable and the gtm.dom trigger ensures that all code has loaded.
We have already tested this with clients on varying degrees of awfullness in terms of GTM implementations.
I am setting up Google Analytics Ecommerce tracking for a client who hosts their shopping cart on Shopify. I have the integration working just fine, except that Shopify's total revenue per order needs to be divided by 100 for it to be accurate. For example, an order comes in with $8.72 in revenue, but the value passed to Google Analytics is 872.
Here is the entire code for bringing Shopify's data into Google Analytics. The field I need to divide by 100 is {{ total_price }}.
<!-- Begin Google Analytics Ecommerce Tracking -->
<script>
ga('require', 'ecommerce');
ga('ecommerce:addTransaction', {
'id': '{{ id }}', // Transaction ID. Required.
'affiliation': 'myClient', // Affiliation or store name.
'revenue': '{{ total_price }}', // Total revenue.
'shipping': '{{ order.shipping_price }}', // Shipping.
'tax': '{{ order.tax_price }}' // Tax.
'currency': 'USD' // Local currency.
});
ga('ecommerce:send');
</script>
I was able to find a different solution. Shopify provides a filter called "money_without_currency" that somehow adds a decimal in the right place, effectively dividing the amount by 100. Silly. So, I never needed to use javascript for the solution. Thanks for the help anyways!
You can do the calculation right in there, as it's standard JS:
ga('ecommerce:addTransaction',{
// some parameters
'revenue': {{total_price}}/100,
// some other parameters
});