How to push a custom variable to GA using dataLayer - google-analytics

I need to push a custom variable to GA ( _setCustomVar ) using the dataLayer. I have read multiple posts on the subject, and they mention the More Options -> Custome Variables when setting up the Google Analytics tag (I assume they are talking about what is now called Classic Google Analytics, because Universal Analytics does not have a More Options).
The thing that is missing in all those posts, is what Track Type do I choose for that?? There is Pageview, Event, Transaction, etc.
Thank you,
Michel

Custom Var is only applicable to Classic Google Analytics under GTM.
If you are using Universal Analytics then you'll need to use Custom Dimensions and not Custom Variables.
You'll first need to configure the Custom Dimension in Admin > Property Level > Custom Definition > Custom Dimensions
Then you can easily pass any value in this Custom Dimension slot using GTM "More options"

You could push the CustomVar independedly.
_gaq.push(['_setCustomVar',
1,                   // This custom var is set to slot #1.  Required parameter.
'Section',           // The top-level name for your online content categories.  Required parameter.
Life & Style',  // Sets the value of "Section" to "Life & Style" for this particular aricle.  Required parameter.
3                    // Sets the scope to page-level.  Optional parameter.
]);
See https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables

Related

Firebase security rules variables use

I'm implementing a security rule to check the data structure for all data of all collections.
for that i created a "data model" collection and want to check if the data to be stored has the same "structure".
After that the idea is to compare the incoming data with it:
function checkDataModel (collectionId, docKeys){
let standardDocKeys = get(/databases/$(database)/documents/data-models/$(collectionId)).data.keys();
let isValid = standardDocKeys.hasAll(docKeys);
return isValid
}
the docKeys param is an array with all the keys in the document to be stored.
After that I would call the function and expect a boolean result.
The problem is that I'm getting those red arrows under the function name and the get method:
red arrows
I think it's some syntax error, but i really could not find the proper way to write it.
the following code from firebase docs is the best reference I could find:
function isAdmin(userId) {
  return exists(/databases/$(database)/documents/admins/$(userId));
}
function isAuthorOrAdmin(userId, article) {
  let isAuthor = article.author == userId;
  // `||` is short-circuiting; isAdmin called only if isAuthor == false.
  return isAuthor || isAdmin(userId);
}

Google Analytics API: Report dimensions and metrics are null

I am using the sample code from https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php, and printResults is failing because $dimensionHeaders and $dimensions are null
Also, it seems to only work if "ga:" is prepended to the view ID provided by google analytics admin\view\view settings\view ID. Is that correct, or am I using the wrong view ID?
Yes, the correct View ID is what the Google Analytics admin interface is in:
Admin --> View --> View settings --> View ID
Like this:
Google's sample code is missing this key bit in getReport() underneath the line: $request = new Google_Service_AnalyticsReporting_ReportRequest();
//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");
$request->setDimensions(array($browser));

Consolidate duplicate URLs analytics with Canonical URLs when using Google Tag Manager

I have GTM installed on my site. We already have canonical URLs on all of our pages, but Google Analytics is not tracking the canonical URLs, so the analytics are getting duplicate pages where the capitalization or querystrings are different. I've found answers on how to modify the Google Analytics snippet to track canonical URLs, such as this answer here, but the issue is that because I have GTM installed my code doesn't have the Google Analytics snippet. Instead, we have a GTM snippet:
<!-- Google Tag Manager -->
<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 =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', <asp:Literal runat="server" id="gtmTag" />);</script>
<!-- End Google Tag Manager -->
How do I make Google Analytics use the canonical URL when I'm using GTM?
Create a DOM type variable to get the canonical link (choose "CSS Selector", the proper Selector should be along the lines of link[rel='canonical']). Expand the "format value" section, check "Convert 'undefined' to" and enter the page url variable as value (so this will return a value even when a page does not have a canonical). Create an Url Variable, set "component type" to "page path", and in "more settings" use the previously created DOM variable as URL source (all this might be a bit overkill, but should be reliable even with missing canonical tags).
In you Analytics tag or your GA settings variable expand the "More Settings" section, expand "fields to set" (which allows you to set properties of the GA tracker), enter "page" as field name and the variable created above as value. This will set the page path value ("page" in Google Analytics) to the canonical value (or default value) extracted above.

Google Analytics dimension pagePathLevel more than 4

I have very long web pages paths reported to google analytics:
/#/legends_g01/games/legends_g01_02_academy_i-170909-55/notes/1/dynamics
/#/legends_02_academy_i/games/legends_g01_02_academy_i-170912-64/notes/12/players
/#/legends_05/games/legends_05-170912-84/notes/22/players
/#/legends_g01_02_academy_i/games/legends_g01_02_academy_i-170919-78/notes/34/levels
I'm using Core API to create a query where I need to have a metric ga:users with dimension by the last path part (7th). The starting part of the path doesn't matter here and should be ignored.
So if there is ga:pagePathLevel7 then I can use
dimension: ga:pagePathLevel7
metrics: ga:users
And see the result like this:
dynamics: 34
players: 45
levels: 87
How can I do this without ga:pagePathLevel7?
It seems that I'm the only one here with such a problem.
As I failed to find a direct solution I ended up adding custom dimensions to my google analytics. I added the dimensions for the last important path parts and changed the code on the site to supply this data together with the pageView url.
import ReactGA from 'react-ga';
export const statDimension = (dimensionName, value) => {
if(value)
{
let obj = {};
obj[dimensionName] = value;
ReactGA.set(obj);
}
};
export const statPageView = (url, game_id, clip_num) => {
if(!url)
{
url = window.location.hash;
}
//set game_id
statDimension(STAT_DIM_GAME_ID, game_id);
//set clip number
statDimension(STAT_DIM_CLIP_NUM, clip_num);
ReactGA.pageview(url);
return null;
};
I use react-ga npm module for submitting data to google analytics.
Now I can use custom dimensions together with filters on my urls to get stats based on the parts of the path with depth > 4.
May be that's not an elegant solution but is a working one.
Hope this will be helpful for somebody like me.

Unable to Push Custom Variables w/ Google Tag Manager to GA

I am trying to build remarketing audience lists within Google Analytics using GTM. I need some help figuring out how to pass custom variables via GTM thru the datalayer and into GA.
So far, I have been able to successfully do this by hard coding some custom code and passing custom variables directly into GA (bypassing GTM). However, when I use this code it skews the GA numbers b/c 2 instances of the same GA that are present via custom code, and existing GTM instance. Which is great since it inflates the numbers favorably ;) Unfortunately, we are currently very dependent GTM, and therefore cannot abandon it.
What we are now trying to do is modify the working code to use with GTM so that we are not inflating our numbers as mentioned. Thus far, we can see this data in the datalayer by inspecting the console in chrome. However, we haven’t been able to push this data to GA.
Here is an example of the code that we used previously which does not rely on GTM and is successfully pushing the custom variables to GA.
<script>var _gaq = _gaq || [];_gaq.push(["_setAccount", "UA-XXXXXX-X"]);_gaq.push(['_setCustomVar', 1, "Category", "testing", 3]);_gaq.push(['_setCustomVar', 2, "content-type", "Brief", 3]);_gaq.push(['_setCustomVar', 3, "publish-date", "Wednesday, July 16, 2014 - 17:42", 3]);_gaq.push(['_setCustomVar', 4, "author", "Greg Bates", 3]);_gaq.push(["_trackPageview"]);(function() {var ga = document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(ga, s);})();</script>
For the current GTM implementation, there is a bit of a hybridization using GTM and hard coding a newer script which I will detail below.
In my standard GA tag for GTM it is setup as follows:
Tag Name: GA Universal
Tag Type: universal analytics
Tracking ID: UA-XXXXXX-X
Enable Display Advertising Features √
Track Type: Page View
Firing Rules: All pages
More Settings>>Custom Dimensions:
Index = 4 Dimension = {{Author}}
Index = 3 Dimension = {{Publish Date}}
Index = 2 Dimension = {{Content Type}}
Index = 1 Dimension = {{Page Category}}
The custom code that is hardcoded into the page manually is as follows:
<script>
if (Drupal.settings.common !== undefined && Drupal.settings.common.pageCategory !== undefined) {
dataLayer = [{
'pageCategory': Drupal.settings.common.pageCategory
}];
var google_tag_params = {
section: Drupal.settings.common.pageCategory,
pagetype: ' ',
membertype: ' '
};
if (Drupal.settings.common.contentType !== undefined) {
dataLayer.push({'contentType': Drupal.settings.common.contentType});
google_tag_params.contenttype = Drupal.settings.common.contentType;
}
if (Drupal.settings.common.publishDate !== undefined) {
dataLayer.push({'publishDate': Drupal.settings.common.publishDate});
google_tag_params.publishdate = Drupal.settings.common.publishDate;
}
if (Drupal.settings.common.author !== undefined) {
dataLayer.push({'author': Drupal.settings.common.author});
google_tag_params.author = Drupal.settings.common.author;
}
}
(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> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
I‘ll also add that Drupal.settings.common.author, Drupal.settings.common.contentType, Drupal.settings.common.pageCategory and Drupal.settings.common.publishDate are defined before executing the GTM script.
Can anybody provide some helpful insight as to what we are doing incorrect and what can be done to pass these custom variables into Google Analytics?
If it would be helpful to see a live implementation, please follow this link http://api.pw/Uem8ba .
Thanks in advance of your time and help!
Brett
ok, first of all, since it's Drupal - drop your custom implementation in favor of these two modules:
https://www.drupal.org/project/google_tag
https://www.drupal.org/project/datalayer
Configure GTM container ID, and pass all the data you need via dataLayer - if after enabling all checkboxes in data_layer module you don't have everything you need in data layer, you have to use alter hook from this module, to push your variables there - since your code is ready it should be very easy.
Next, you have to configure GTM to collect your data in GTM and pass it to GA, so:
add a macro choosing "dataLayer variable" as a type
put variable name in the input and name it (it'd be best to name it in the same way for debuging purposes)
repeat 1 and 2 for remaining 3 dimensions
edit your standard GTM GA tag by expanding "more options->custom dimensions" and add there your dimension numbers and varaibles you've configured in steps 1-3.
save updated tag and click "preview button" to launch your site with GTM debug bar at the bottom
check in the debug bar if your data has been passed to dataLayer and then if variables were matched and passed on to GA
nobody said using GTM is simple ;)

Resources