I have this code on google analytics API v4 with PHP.
$eCPM_Adsense = new Google_Service_AnalyticsReporting_Metric();
$eCPM_Adsense->setExpression("ga:adsenseECPM");
$eCPM_Adsense->setAlias("eCPM Adsense");
// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setFieldName("ga:adsenseECPM");
$ordering->setOrderType("VALUE");
$ordering->setSortOrder("DESCENDING");
The Ordering not works for me. Can you help me? Thanks
the problem is that you need to have the setOrderBys() on the request. This is not detailed on the API documentation...
an example
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setFieldName("ga:pageviews");
$ordering->setOrderType("VALUE");
$ordering->setSortOrder("DESCENDING");
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($path));
$request->setMetrics(array($sessions));
$request->setOrderBys($ordering); // note this one!
OrderBy method is not explained well in Google Documentation. The only example they have in Reporting API v4 is that
// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("HISTOGRAM_BUCKET");
$ordering->setFieldName("ga:sessionCount");
here is an example for getReport($analytics)
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("30daysAgo");
$dateRange->setEndDate("yesterday");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:searchUniques");
$sessions->setAlias("searchKeyword");
//Create the Dimensions object.
$searchKeyword = new Google_Service_AnalyticsReporting_Dimension();
$searchKeyword->setName("ga:searchKeyword");
// Create order object
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setFieldName("ga:searchUniques");
$ordering->setOrderType("VALUE");
$ordering->setSortOrder("DESCENDING"); //There is no "-" usage
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($searchKeyword));
$request->setMetrics(array($sessions));
$request->setOrderBys($ordering); //Must be added
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
It's also not mentioned under migration documents. Hope It's going to be updated soon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With