PluginProbe ʕ •ᴥ•ʔ
ShareThis Dashboard for Google Analytics / 3.1.2
ShareThis Dashboard for Google Analytics v3.1.2
3.3.2 trunk 1.0.7 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.1 2.1.2 2.1.3 2.1.4 2.1.5 2.2.5 2.3.5 2.3.6 2.3.7 2.3.8 2.4.0 2.4.1 2.5.0 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 3.0.0 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.1.5 3.1.6 3.1.7 3.2.0 3.2.1 3.2.2 3.2.3 3.2.4 3.3.0 3.3.1
googleanalytics / view / templates / ga4-dashboard.php
googleanalytics / view / templates Last commit date
sidebar 3 years ago appearance.php 4 years ago date-custom-range-filter.php 4 years ago demo-popup.php 4 years ago demographic-chart.php 4 years ago demographic.php 4 years ago exclusions.php 4 years ago ga4-dashboard.php 3 years ago ga4-demographic-chart.php 3 years ago gdpr-config.php 4 years ago gdpr.php 4 years ago purposes.php 4 years ago
ga4-dashboard.php
405 lines
1 <?php
2
3 use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
4 use Google\Analytics\Data\V1beta\DateRange;
5 use Google\Analytics\Data\V1beta\Dimension;
6 use Google\Analytics\Data\V1beta\Metric;
7 use Google\Analytics\Data\V1beta\OrderBy;
8
9 $credentials = GOOGLE_APPLICATION_CREDENTIALS;
10 $myfile = file_get_contents($credentials, "r");
11 $client_obj = json_decode($myfile);
12 $client = Ga_Admin::getGa4Client();
13 $token_response = $client->getAccessToken();
14 $client_stuff = (array) $client;
15 $client_obj = array_values($client_stuff)[4];
16 $ga4_property = get_option('googleanalytics-ga4-property');
17 $ga4_demo = get_option('googleanalytics-ga4-demo');
18 $page_list_count_data = [];
19 $gender_count_data = [];
20 $age_count_data = [];
21 $analytics_service = new BetaAnalyticsDataClient( [
22 'credentials' => Google\ApiCore\CredentialsWrapper::build( [
23 'scopes' => [
24 'https://www.googleapis.com/auth/analytics.readonly',
25 ],
26 'keyFile' => [
27 'type' => 'authorized_user',
28 'client_id' => $client_obj['client_id'],
29 'client_secret' => $client_obj['client_secret'],
30 'refresh_token' => $token_response["access_token"]
31 ],
32 ] ),
33 ] );
34
35 $from = false === empty($date_range['from']) ? $date_range['from'] : '8daysAgo';
36 $to = false === empty($date_range['to']) ? $date_range['to'] : 'today';
37
38 $response = $analytics_service->runReport([
39 'property' => $ga4_property,
40 'dateRanges' => [
41 new DateRange([
42 'start_date' => $from,
43 'end_date' => $to,
44 ]),
45 ],
46 'dimensions' => [
47 new Dimension(['name' => 'date']),
48 ],
49 'metrics' => [
50 new Metric(['name' => 'screenPageViews',]),
51 ],
52 'orderBys' => [
53 new OrderBy([
54 'dimension' => new OrderBy\DimensionOrderBy([
55 'dimension_name' => 'date', // your dimension here
56 'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
57 ]),
58 'desc' => false,
59 ]),
60 ],
61 ]);
62
63 $page_list_response = $analytics_service->runReport([
64 'property' => $ga4_property,
65 'dateRanges' => [
66 new DateRange([
67 'start_date' => $from,
68 'end_date' => $to,
69 ]),
70 ],
71 'dimensions' => [
72 new Dimension(['name' => 'landingPage']),
73 ],
74 'metrics' => [
75 new Metric(['name' => 'screenPageViews',]),
76 ],
77 ]);
78
79 foreach ($page_list_response->getRows() as $row) :
80 $metrics = $row->getMetricValues();
81
82 foreach ($row->getDimensionValues() as $index => $dimension_value) :
83 $page = $dimension_value->getValue();
84 $page_list_count_data[$page] = $metrics[$index]->getValue();
85 endforeach;
86 endforeach;
87
88 $pageViewCount = array_sum(array_values($page_list_count_data));
89
90 $user_response = $analytics_service->runReport([
91 'property' => $ga4_property,
92 'dateRanges' => [
93 new DateRange([
94 'start_date' => $from,
95 'end_date' => $to,
96 ]),
97 ],
98 'dimensions' => [
99 new Dimension(['name' => 'date',]),
100 ],
101 'metrics' => [
102 new Metric(['name' => 'newUsers',]),
103 ],
104 'orderBys' => [
105 new OrderBy([
106 'dimension' => new OrderBy\DimensionOrderBy([
107 'dimension_name' => 'date', // your dimension here
108 'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
109 ]),
110 'desc' => false,
111 ]),
112 ],
113 ]);
114
115 $gender_chart_response = $analytics_service->runReport([
116 'property' => $ga4_property,
117 'dateRanges' => [
118 new DateRange([
119 'start_date' => $from,
120 'end_date' => $to,
121 ]),
122 ],
123 'dimensions' => [
124 new Dimension(['name' => 'userGender',]),
125 ],
126 'metrics' => [
127 new Metric(['name' => 'newUsers',]),
128 ],
129 ]);
130
131 $age_chart_response = $analytics_service->runReport([
132 'property' => $ga4_property,
133 'dateRanges' => [
134 new DateRange([
135 'start_date' => $from,
136 'end_date' => $to,
137 ]),
138 ],
139 'dimensions' => [
140 new Dimension(['name' => 'userAgeBracket',]),
141 ],
142 'metrics' => [
143 new Metric(['name' => 'newUsers',]),
144 ],
145 ]);
146
147 foreach ($gender_chart_response->getRows() as $gender_row) :
148 $metrics = $gender_row->getMetricValues();
149
150 foreach ($gender_row->getDimensionValues() as $index => $dimension_value) :
151 $page = $dimension_value->getValue();
152
153 if ('unknown' !== $page) {
154 $gender_count_data[$page] = $metrics[$index]->getValue();
155 }
156 endforeach;
157 endforeach;
158
159 $gender_count_data = array_reverse($gender_count_data);
160
161 foreach ($age_chart_response->getRows() as $gender_row) :
162 $metrics = $gender_row->getMetricValues();
163
164 foreach ($gender_row->getDimensionValues() as $index => $dimension_value) :
165 $page = $dimension_value->getValue();
166
167 if ('unknown' !== $page) {
168 $age_count_data[$page] = $metrics[$index]->getValue();
169 }
170 endforeach;
171 endforeach;
172
173 $ga4_device_chart_response = $analytics_service->runReport([
174 'property' => $ga4_property,
175 'dateRanges' => [
176 new DateRange([
177 'start_date' => $from,
178 'end_date' => $to,
179 ]),
180 ],
181 'dimensions' => [
182 new Dimension(['name' => 'deviceCategory',]),
183 ],
184 'metrics' => [
185 new Metric(['name' => 'newUsers',]),
186 ],
187 ]);
188
189 foreach ($ga4_device_chart_response->getRows() as $device_row) :
190 $metrics = $device_row->getMetricValues();
191
192 foreach ($device_row->getDimensionValues() as $index => $dimension_value) :
193 $page = $dimension_value->getValue();
194 $ga4_demo_device_data[$page] = $metrics[$index]->getValue();
195 endforeach;
196 endforeach;
197
198 $x = 1;
199 ?>
200 <script type="text/javascript">
201 ga_charts.init( function() {
202 const pageSessionData = new google.visualization.DataTable();
203 const userData = new google.visualization.DataTable();
204
205 pageSessionData.addColumn( 'string', '<?php echo esc_js( __( 'Day', 'googleanalytics' ) ); ?>' );
206 pageSessionData.addColumn( 'number', '<?php echo esc_js( __( 'Page Views', 'googleanalytics' ) ); ?>' );
207 pageSessionData.addColumn( { type: 'string', role: 'tooltip', 'p': { 'html': true } } );
208
209 userData.addColumn( 'string', '<?php echo esc_js( __( 'Day', 'googleanalytics' ) ); ?>' );
210 userData.addColumn( 'number', '<?php echo esc_js( __( 'New Users', 'googleanalytics' ) ); ?>' );
211 userData.addColumn( { type: 'string', role: 'tooltip', 'p': { 'html': true } } );
212
213 <?php foreach ($response->getRows() as $row) :
214 $metrics = $row->getMetricValues();
215
216 foreach ($row->getDimensionValues() as $index => $dimension_value) :
217 $date = date('M d', strtotime($dimension_value->getValue()));
218 $page_session_count_data[$date] = $metrics[$index]->getValue();
219 endforeach;
220 endforeach;
221
222 foreach ($user_response->getRows() as $user_row) :
223 $metrics = $user_row->getMetricValues();
224
225 foreach ($user_row->getDimensionValues() as $index => $dimension_value) :
226 $date = date('M d', strtotime($dimension_value->getValue()));
227
228 $user_count_data[$date] = $metrics[$index]->getValue();
229 endforeach;
230 endforeach;
231 ?>
232
233 // Page Sessions.
234 <?php foreach($page_session_count_data as $date => $value) : ?>
235 pageSessionData.addRow( [
236 '<?php echo esc_js($date); ?>',
237 <?php echo esc_js( $value ); ?>,
238 ga_charts.createPageTooltip( '<?php echo esc_js($date); ?>',
239 '<?php echo esc_js( $value ); ?>'
240 )
241 ] );
242 <?php endforeach; ?>
243
244 // User data.
245 <?php foreach($user_count_data as $date => $value) : ?>
246 userData.addRow( [
247 '<?php echo esc_js($date); ?>',
248 <?php echo esc_js( $value ); ?>,
249 ga_charts.createUserTooltip( '<?php echo esc_js($date); ?>',
250 '<?php echo esc_js( $value ); ?>'
251 )
252 ] );
253 <?php endforeach; ?>
254
255 ga_charts.events( pageSessionData );
256 ga_charts.drawPageSessionChart( pageSessionData );
257 ga_charts.drawUserChart( userData );
258
259 // GA4 Demographic gender chart.
260 <?php
261 $demo_gender_data[0] = array( 'Gender', 'The gender of visitors' );
262
263 $x = 1;
264 foreach ( $gender_count_data as $gender_type => $amount ) {
265 $demo_gender_data[ $x ] = array( ucfirst( $gender_type ), intval( $amount ) );
266 $x ++;
267 }
268 ?>
269
270 ga_charts.drawDemoGenderGa4Chart(<?php echo wp_json_encode( $demo_gender_data ); ?>);
271 ga_loader.hide();
272
273 // Demographic age chart
274 <?php
275 $demo_ga4_age_data[0] = array( 'Age', 'Average age range of visitors' );
276
277 $x = 1;
278
279 foreach ( $age_count_data as $age_type => $amount ) {
280 $demo_ga4_age_data[ $x ] = array( $age_type, intval( $amount ) );
281 $x ++;
282 }
283 ?>
284 ga_charts.drawDemoAgeGa4Chart(<?php echo wp_json_encode( $demo_ga4_age_data ); ?>);
285
286 // Device chart.
287 <?php
288 $ga4_demo_count_data = array();
289 $ga4_demo_count_data[0] = array(
290 __( 'Device', 'googleanalytics' ),
291 __( 'Device Breakdown', 'googleanalytics' ),
292 );
293
294 $x = 1;
295 foreach ( $ga4_demo_device_data as $age_type => $amount ) {
296 $ga4_demo_count_data[ $x ] = array( $age_type, intval( $amount ) );
297 $x ++;
298 }
299 ?>
300 ga_charts.drawGa4DemoDeviceChart(<?php echo wp_json_encode($ga4_demo_count_data); ?>);
301
302 ga_loader.hide();
303 } );
304 </script>
305 <div class="dashboard-title">GA4 Dashboard</div>
306
307 <?php
308 if (true === empty($page_list_count_data)) :
309 echo wp_kses(
310 Ga_Helper::ga_wp_notice(
311 __( 'You don\'t appear to have enough page view data. Please come back at a later date once you do.' ),
312 'warning',
313 false,
314 array(
315
316 )
317 ),
318 array(
319 'button' => array(
320 'class' => array(),
321 'onclick' => array(),
322 ),
323 'div' => array(
324 'class' => array(),
325 ),
326 'p' => array(),
327 )
328 );
329 else :
330 ?>
331 <div id="page_session_chart_div"></div>
332
333 <?php require plugin_dir_path( __FILE__ ) . 'ga4-demographic-chart.php'; ?>
334
335 <div class="ga-panel ga-panel-default" style="width:100%; max-width:1210px; margin-top: 2rem;">
336 <div class="ga-panel-heading">
337 <strong><?php echo esc_html( 'Top 10 Pages/Posts by page views' ); ?></strong>
338 </div>
339 <div class="ga-panel-body">
340 <div id="table-container">
341 <table class="ga-table">
342 <tr>
343 <th style="text-align: right;">
344 <?php echo esc_html( 'Url' ); ?>
345 </th>
346 <th style="text-align: right;">
347 <?php echo esc_html( 'Pageviews' ); ?>
348 </th>
349 <th style="text-align: right;">
350 <?php echo '%'; ?>
351 </th>
352 </tr>
353 <?php foreach ( array_slice($page_list_count_data, 0, 10) as $page => $metric ) :
354 $percentage = round((float)($metric / $pageViewCount) * 100 )
355 ?>
356 <tr>
357 <td class="ga-col-name">
358 <?php
359 if ( '(direct) / (none)' !== $page ) :
360 $single_breakdown = false === empty( $ts ) ?
361 '/explorer-table.plotKeys=%5B%5D&_r.drilldown=analytics.sourceMedium:' :
362 '/explorer-table.plotKeys=%5B%5D&_r.drilldown=analytics.pagePath:';
363 ?>
364 <a class="ga-source-name"
365 href="
366 <?php
367 echo esc_url(
368 $page . $single_breakdown . str_replace(
369 '+',
370 '%20',
371 str_replace(
372 '2F',
373 '~2F',
374 str_replace( '%', '', rawurlencode( $page ) )
375 )
376 )
377 );
378 ?>
379 /"
380 target="_blank"><?php echo esc_html( $page ); ?></a>
381 <?php else : ?>
382 <?php echo esc_html( $page ); ?>
383 <?php endif; ?>
384 </td>
385 <td style="text-align: right"><?php echo esc_html( $metric ); ?></td>
386 <td>
387 <div class="progress">
388 <div class="progress-bar" role="progressbar"
389 aria-valuenow="<?php echo esc_attr( $percentage ); ?>" aria-valuemin="0"
390 aria-valuemax="100"
391 style="width: <?php echo esc_attr( $percentage ); ?>%;"></div>
392 <span style="margin-left: 10px;">
393 <?php echo esc_html( Ga_Helper::format_percent( $percentage ) ); ?>
394 </span>
395 </div>
396 </td>
397 </tr>
398 <?php endforeach; ?>
399 </table>
400 </div>
401 </div>
402 </div>
403 <?php endif; ?>
404 <div id="user_chart_div"></div>
405