← All changes
|
includes/integrations/class-google-analytics-client.php
+14
-4
2.14.0
→
2.14.2
View file →
| @@ -120,8 +120,16 @@ | ||
| 120 | 120 | |
| 121 | 121 | /** |
| 122 | 122 | * Run analytics report for specified metrics and date range |
| 123 | 123 | * |
| 124 | + * The window is exactly `$date_range` days long and ends yesterday (UTC): | |
| 125 | + * "30d" is the 30 complete days before today. GA4's startDate and endDate | |
| 126 | + * are both inclusive, so the start is `days - 1` days before the end. | |
| 127 | + * Today is left out because it is a partial day, which is also what | |
| 128 | + * GA4's own "Last 30 days" does. Search Console ends two days earlier | |
| 129 | + * (D-2) because its data lags; GA4's does not, so it is not held back | |
| 130 | + * to match (#923). | |
| 131 | + * | |
| 124 | 132 | * @param string $date_range Date range ('7d', '30d', '90d') |
| 125 | 133 | * @param array $metrics Metrics to retrieve (GA4 metric names) |
| 126 | 134 | * @param array $dimensions Dimensions to group by |
| 127 | 135 | * @return array Analytics report data |
| @@ -129,12 +137,14 @@ | ||
| 129 | 137 | */ |
| 130 | 138 | public function run_report(string $date_range = '30d', array $metrics = ['sessions'], array $dimensions = []): array { |
| 131 | 139 | $endpoint = "/{$this->property_id}:runReport"; |
| 132 | 140 | |
| 133 | - // Convert date range to start/end dates | |
| 134 | - $end_date = gmdate('Y-m-d'); | |
| 135 | - $days = (int) str_replace('d', '', $date_range); | |
| 136 | - $start_date = gmdate('Y-m-d', strtotime("-{$days} days")); | |
| 141 | + // Convert date range to start/end dates, from one anchor so a request | |
| 142 | + // straddling midnight cannot mix two days. | |
| 143 | + $days = max(1, (int) str_replace('d', '', $date_range)); | |
| 144 | + $end_ts = strtotime('-1 day', time()); | |
| 145 | + $end_date = gmdate('Y-m-d', $end_ts); | |
| 146 | + $start_date = gmdate('Y-m-d', strtotime('-' . ($days - 1) . ' days', $end_ts)); | |
| 137 | 147 | |
| 138 | 148 | $request_body = [ |
| 139 | 149 | 'dateRanges' => [ |
| 140 | 150 | [ |