Search code examples
google-analytics-apigoogle-tag-managergoogle-api-php-client

how to query custom dimension google anaylitics api


I have setup a custom dimension in google analytics 'dimension2' into which I want to capture a WPForms UniqueID. I added this to Google Tag manager and I can see the custom dimension with a value when I preview site in GTA preview. . I added this to gtags.js on this word press site,

    var dimensionValue = $.cookie("_wpfuuid");

    gtag('config', 'UA-1234567890-2', {
      'custom_map': {'dimension2': 'wpfid'}
    });

    gtag('set', 'dimension2', {'wpfid': dimensionValue});

In google analytics query explorer, I can see dimension2 in the test results.

"columnHeaders": [
{
  "name": "ga:dimension2",
  "columnType": "DIMENSION",
  "dataType": "STRING"
},
{
  "name": "ga:users",
  "columnType": "METRIC",
  "dataType": "INTEGER"
}
],
"totalsForAllResults": {
   "ga:users": "1"
},
"rows": [
  [
    "40502794-ecf1-4cf6-97b9-2c16c7f6c949",
    "1"
  ]
]

And, I can see the dimension2 data in google analytics user explorer, so it is making it to the browser interface for analytics.

However, when I add the following to my API query script, it breaks and is not generating any php errors, or the error is that it does not recognize 'dimension2'. I tried this on 2 views and both act the same. Here is my code to add the custom dimension to my query

$dimension = new Google_Service_AnalyticsReporting_Dimension();
$dimension->setName("ga:dimension2");

What am I missing? Why isn't this visible in google api results and/or where I can I see any errors?


Solution

  • Some hours later, this code started to work, which suggests to me that custom dimensions are not immediately available to the api. In this case the api recognized dimension2 long after the data was visible in the analytics website.

    Second possibility to check which can cause this seemingly good code to not work, you are using the wrong view id. Of the 2 views I tested, this only works on one.