How to find Organic search data using google analytics 4 data API?

868 Views Asked by At

I'm using the google analytics 4 API to retrieve the analytics data. While I'm having an issue to retrieve the Organic search data. Working code for other metrics.

$response = $this->data_client->runReport([
  'property' => $propertyId,
  'dateRanges' => [new DateRange(['start_date' => '7daysAgo', 'end_date' => '1daysAgo'])],
  'metrics' => [
    new Metric(['name' => 'totalUsers']),
    new Metric(['name' => 'newUsers']),
    new Metric(['name' => 'sessions']),
    new Metric(['name' => 'screenPageViews']),
    new Metric(['name' => 'engagedSessions']),
    new Metric(['name' => 'activeUsers']),
  ],
  // 'dimensions' => [
  //   new Dimension(['name' => 'streamName']),
  //   ]
]);

foreach ($response->getRows() as $row) {
  foreach ($row->getDimensionValues() as $dimensionValue) {
    print 'Dimension Value: ' . $dimensionValue->getValue() . PHP_EOL;
  }
  foreach ($row->getMetricValues() as $metricValue) {
    print 'Metric Value: ' . $metricValue->getValue() . PHP_EOL;
  }
}

I'm trying to use the defaultChannelGrouping to retrieve the organic search but not getting any useful documents how to do. Sample code which is not working.

 $response = $this->data_client->runReport([
  'property' => $propertyId,
  'dateRanges' => [new DateRange(['start_date' => '7daysAgo', 'end_date' => '1daysAgo'])],
  'dimensions' => [
    new Dimension(['name' => 'defaultChannelGrouping']),
  ]
]);

foreach ($response->getRows() as $row) {
  foreach ($row->getDimensionValues() as $dimensionValue) {
    print 'Dimension Value: ' . $dimensionValue->getValue() . "<br/>";
  }
}
1

There are 1 best solutions below

0
Brett On

Try using sessionDefaultChannelGrouping rather than defaultChannelGrouping.

In the migration guides, GA4 recommends using sessionDefaultChannelGrouping in GA4 where you might have used ga:channelGrouping in Universal Analytics.

defaultChannelGrouping is an attribution dimension. If your GA4 property's event attribution model is Data-driven, defaultChannelGrouping will return no rows if your GA4 property has not had a conversion in the date range.