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/>";
}
}
Try using
sessionDefaultChannelGroupingrather thandefaultChannelGrouping.In the migration guides, GA4 recommends using
sessionDefaultChannelGroupingin GA4 where you might have usedga:channelGroupingin Universal Analytics.defaultChannelGroupingis an attribution dimension. If your GA4 property's event attribution model is Data-driven,defaultChannelGroupingwill return no rows if your GA4 property has not had a conversion in the date range.