846 lines
26 KiB
PHP
846 lines
26 KiB
PHP
<?php
|
|
|
|
|
|
/*
|
|
Plugin Name: SIGE Analytics
|
|
Plugin URI: https://www.sige.ita.br
|
|
Description: Google Analytics
|
|
Author: Leandro Geraldo da Costa
|
|
version: 1.0
|
|
*
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
|
|
// Load the Google API PHP Client Library.
|
|
require_once plugin_dir_path( __FILE__ ) . '/vendor/autoload.php';
|
|
|
|
function initializeAnalytics()
|
|
{
|
|
|
|
// Use the developers console and download your service account
|
|
// credentials in JSON format. Place them in this directory or
|
|
// change the key file location if necessary.
|
|
$KEY_FILE_LOCATION = plugin_dir_path( __FILE__ ) . 'key.json';
|
|
|
|
// Create and configure a new client object.
|
|
$client = new Google_Client();
|
|
$client->setApplicationName("Hello Analytics Reporting");
|
|
$client->setAuthConfig($KEY_FILE_LOCATION);
|
|
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
|
|
$analytics = new Google_Service_AnalyticsReporting($client);
|
|
|
|
return $analytics;
|
|
}
|
|
|
|
function getReport($analytics, $start_date, $end_date) {
|
|
|
|
// Replace with your view ID, for example XXXX.
|
|
$VIEW_ID = "436681896";
|
|
|
|
// Create the DateRange object.
|
|
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
|
|
$dateRange->setStartDate("start_date");
|
|
$dateRange->setEndDate("end_date");
|
|
|
|
// Create the Metrics object.
|
|
$sessions = new Google_Service_AnalyticsReporting_Metric();
|
|
$sessions->setExpression("ga:sessions");
|
|
$sessions->setAlias("sessions");
|
|
|
|
// Create the Metrics object.
|
|
$users = new Google_Service_AnalyticsReporting_Metric();
|
|
$users->setExpression("ga:users");
|
|
$users->setAlias("users");
|
|
|
|
// Create the Metrics object.
|
|
$organicSearches = new Google_Service_AnalyticsReporting_Metric();
|
|
$organicSearches->setExpression("ga:organicSearches");
|
|
$organicSearches->setAlias("organicSearches");
|
|
|
|
// Create the Metrics object.
|
|
$avgPageLoadTime = new Google_Service_AnalyticsReporting_Metric();
|
|
$avgPageLoadTime->setExpression("ga:avgPageLoadTime");
|
|
$avgPageLoadTime->setAlias("avgPageLoadTime");
|
|
|
|
// Create the ReportRequest object.
|
|
$request = new Google_Service_AnalyticsReporting_ReportRequest();
|
|
$request->setViewId($VIEW_ID);
|
|
$request->setDateRanges($dateRange);
|
|
$request->setMetrics(array($sessions,$users,$organicSearches,$avgPageLoadTime));
|
|
|
|
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
|
|
$body->setReportRequests( array( $request) );
|
|
return $analytics->reports->batchGet( $body );
|
|
}
|
|
|
|
// function getLatestData($data){
|
|
// $analytics = initializeAnalytics();
|
|
// $i = 0;
|
|
// for($j = 6;$j>0; $j--){
|
|
// $start_date = date('Y-m',strtotime("-$j month")) . '-01';
|
|
// $d = new DateTime($start_date);
|
|
// $end_date = $d->format('Y-m-t');
|
|
// }
|
|
// }
|
|
|
|
$analytics = initializeAnalytics();
|
|
$result = getReport($analytics, '2024-01-01','2024-05-01');
|
|
|
|
print_r($result);
|
|
|
|
|
|
/*
|
|
|
|
// Report all PHP errors
|
|
|
|
putenv("GOOGLE_APPLICATION_CREDENTIALS=" . __DIR__ . '/key.json');
|
|
error_reporting(E_ALL);
|
|
ini_set('display_errors', '1');
|
|
|
|
require_once __DIR__ . '/vendor/autoload.php';
|
|
|
|
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
|
|
use Google\Analytics\Data\V1beta\DateRange;
|
|
use Google\Analytics\Data\V1beta\Dimension;
|
|
use Google\Analytics\Data\V1beta\Metric;
|
|
|
|
function google_analytics_report_shortcode($atts) {
|
|
// Extract shortcode attributes
|
|
$atts = shortcode_atts(array(
|
|
'property_id' => '436681896'
|
|
), $atts);
|
|
|
|
// Initialize BetaAnalyticsDataClient
|
|
$client = new BetaAnalyticsDataClient();
|
|
|
|
// Make an API call.
|
|
$response = $client->runReport([
|
|
'property' => 'properties/' . $atts['property_id'],
|
|
'dateRanges' => [
|
|
new DateRange([
|
|
'start_date' => '2023-03-31',
|
|
'end_date' => 'today',
|
|
]),
|
|
],
|
|
'dimensions' => [
|
|
new Dimension(['name' => 'city']),
|
|
],
|
|
'metrics' => [
|
|
new Metric(['name' => 'activeUsers']),
|
|
]
|
|
]);
|
|
|
|
// Prepare output
|
|
$output = '<div class="google-analytics-report">';
|
|
$output .= '<h2>Report result:</h2>';
|
|
$output .= '<ul>';
|
|
|
|
foreach ($response->getRows() as $row) {
|
|
$output .= '<li>' . $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . '</li>';
|
|
}
|
|
|
|
$output .= '</ul>';
|
|
$output .= '</div>';
|
|
|
|
return $output;
|
|
}
|
|
add_shortcode('google_analytics_report', 'google_analytics_report_shortcode');
|
|
|
|
*/
|
|
/*
|
|
Plugin Name: GA4 Connector
|
|
Description: Connects to Google Analytics 4 (GA4) using shortcode.
|
|
Version: 1.0
|
|
Author: Your Name
|
|
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
function fetch_ga4_data() {
|
|
// Include Google API PHP client library
|
|
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
|
|
|
|
// Set your Google Analytics property ID
|
|
$propertyId = '436681896';
|
|
|
|
// Set the path to your service account key file
|
|
$keyFilePath = plugin_dir_path(__FILE__) . 'key.json';
|
|
|
|
// Initialize the Google Client
|
|
$client = new Google_Client();
|
|
|
|
// Set credentials from the service account key file
|
|
$client->setAuthConfig($keyFilePath);
|
|
|
|
// Set the scopes required for the Analytics Reporting API
|
|
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
|
|
|
|
// Create Google Analytics service
|
|
$analytics = new Google_Service_AnalyticsReporting($client);
|
|
|
|
// Fetch GA4 data using the Reporting API
|
|
// You need to implement your own code here to fetch the data you need
|
|
// For example:
|
|
// $response = $analytics->reports->batchGet($yourReportRequest);
|
|
|
|
// Return fetched data (for demonstration purposes)
|
|
return '<p>GA4 Data will be displayed here.</p>';
|
|
}
|
|
|
|
|
|
<?php
|
|
*/
|
|
/*
|
|
Plugin Name: GA4 Connector
|
|
Description: Connects to Google Analytics 4 (GA4) using shortcode.
|
|
Version: 1.0
|
|
Author: Your Name
|
|
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
function fetch_ga4_data() {
|
|
// Set your Google Analytics property ID
|
|
$propertyId = '436681896';
|
|
|
|
// Set your API key
|
|
$apiKey = 'AIzaSyDb0wOoHZt55ONwBKXhVI76n-6u8yGq5tw';
|
|
|
|
// Initialize Google Client
|
|
$client = new GuzzleHttp\Client();
|
|
|
|
// Make request to Google Analytics Data API
|
|
$response = $client->get("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [
|
|
'json' => [
|
|
'reportRequests' => [
|
|
'viewId' => $propertyId,
|
|
// Add your report request configuration here
|
|
]
|
|
]
|
|
]);
|
|
|
|
// Decode response
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
// Process and display data (for demonstration purposes)
|
|
// You need to implement your own logic to process the data
|
|
return '<pre>' . print_r($data, true) . '</pre>';
|
|
}
|
|
|
|
/*
|
|
<?php
|
|
|
|
Plugin Name: GA4 Connector
|
|
Description: Connects to Google Analytics 4 (GA4) using shortcode.
|
|
Version: 1.0
|
|
Author: Your Name
|
|
|
|
|
|
// Include Composer autoloader
|
|
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
function fetch_ga4_data() {
|
|
// Set your Google Analytics property ID
|
|
$propertyId = '436681896';
|
|
|
|
// Set your API key
|
|
$apiKey = 'AIzaSyDb0wOoHZt55ONwBKXhVI76n-6u8yGq5tw';
|
|
|
|
// Initialize GuzzleHttp Client
|
|
$client = new GuzzleHttp\Client();
|
|
|
|
// Make request to Google Analytics Data API
|
|
$response = $client->get("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [
|
|
'json' => [
|
|
'reportRequests' => [
|
|
'viewId' => $propertyId,
|
|
// Add your report request configuration here
|
|
]
|
|
]
|
|
]);
|
|
|
|
// Decode response
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
// Process and display data (for demonstration purposes)
|
|
// You need to implement your own logic to process the data
|
|
return '<pre>' . print_r($data, true) . '</pre>';
|
|
}
|
|
*/
|
|
|
|
/*
|
|
Plugin Name: GA4 Connector
|
|
Description: Connects to Google Analytics 4 (GA4) using shortcode.
|
|
Version: 1.0
|
|
Author: Your Name
|
|
|
|
|
|
// Include Composer autoloader
|
|
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
function fetch_ga4_data() {
|
|
// Set your Google Analytics property ID
|
|
$propertyId = '436681896';
|
|
|
|
// Set your API key
|
|
$apiKey = 'AIzaSyDb0wOoHZt55ONwBKXhVI76n-6u8yGq5tw';
|
|
|
|
// Initialize GuzzleHttp Client
|
|
$client = new GuzzleHttp\Client();
|
|
|
|
try {
|
|
// Make request to Google Analytics Data API
|
|
$response = $client->post("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [
|
|
'json' => [
|
|
'reportRequests' => [
|
|
[
|
|
'viewId' => $propertyId,
|
|
'dateRanges' => [
|
|
'startDate' => '7daysAgo',
|
|
'endDate' => 'today'
|
|
],
|
|
'metrics' => [
|
|
['expression' => 'ga:sessions']
|
|
]
|
|
// Add any other report request configurations as needed
|
|
]
|
|
]
|
|
]
|
|
]);
|
|
|
|
// Decode response
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
// Process and display data (for demonstration purposes)
|
|
// You need to implement your own logic to process the data
|
|
return '<pre>' . print_r($data, true) . '</pre>';
|
|
} catch (Exception $e) {
|
|
return 'Error fetching GA4 data: ' . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
POST https://analyticsdata.googleapis.com/v1beta/properties/436681896:runRealtimeReport
|
|
{
|
|
"dimensions": [{ "name": "country" }],
|
|
"metrics": [{ "name": "activeUsers" }]
|
|
}
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
Plugin Name: GA4 Analytics Plugin
|
|
Description: Fetch GA4 data and display it using a shortcode.
|
|
Version: 1.0
|
|
Author: Your Name
|
|
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'fetch_ga4_data');
|
|
|
|
function fetch_ga4_data() {
|
|
// Include the Firebase JWT library
|
|
require_once plugin_dir_path(__FILE__) . 'JWT.php';
|
|
|
|
// Load the JSON file containing the service account credentials
|
|
$key_file = plugin_dir_path(__FILE__) . 'key.json';
|
|
$key_data = file_get_contents($key_file);
|
|
|
|
// Check if the file was loaded successfully
|
|
if ($key_data === false) {
|
|
return "Error loading service account credentials file.";
|
|
}
|
|
|
|
// Decode the JSON data
|
|
$key_json = json_decode($key_data, true);
|
|
|
|
// Check if JSON decoding was successful
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
return "Error decoding service account credentials: " . json_last_error_msg();
|
|
}
|
|
|
|
// Extract the required fields from the JSON data
|
|
$private_key = $key_json['private_key'];
|
|
$client_email = $key_json['client_email'];
|
|
|
|
// Prepare the JWT payload
|
|
$jwt_payload = array(
|
|
'iss' => $client_email,
|
|
'aud' => 'https://analyticsdata.googleapis.com/',
|
|
'exp' => time() + 3600, // Token expiration time (1 hour from now)
|
|
'iat' => time(), // Token issuance time
|
|
);
|
|
|
|
// Create the JWT
|
|
$jwt = \Firebase\JWT\JWT::encode($jwt_payload, $private_key, 'RS256');
|
|
|
|
// Define the Google Analytics API endpoint
|
|
$endpoint = 'https://analyticsdata.googleapis.com/v1beta/properties/436681896:runRealtimeReport';
|
|
|
|
// Define request body
|
|
$request_body = json_encode(array(
|
|
"dimensions" => array(array("name" => "country")),
|
|
"metrics" => array(array("name" => "activeUsers"))
|
|
));
|
|
|
|
// Make the request using WordPress HTTP API
|
|
$response = wp_remote_post($endpoint, array(
|
|
'body' => $request_body,
|
|
'headers' => array(
|
|
'Authorization' => 'Bearer ' . $jwt,
|
|
'Content-Type' => 'application/json',
|
|
),
|
|
));
|
|
|
|
// Check if the request was successful
|
|
if (is_wp_error($response)) {
|
|
return "Error fetching data: " . $response->get_error_message();
|
|
} else {
|
|
$body = wp_remote_retrieve_body($response);
|
|
$data = json_decode($body, true);
|
|
|
|
// Process and display the data as needed
|
|
// For example, you could return a formatted output
|
|
$output = "<h2>GA4 Data</h2>";
|
|
$output .= "<pre>" . print_r($data, true) . "</pre>";
|
|
|
|
return $output;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function run_analytics_report() {
|
|
|
|
require 'vendor/autoload.php';
|
|
|
|
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
|
|
use Google\Analytics\Data\V1beta\DateRange;
|
|
use Google\Analytics\Data\V1beta\Dimension;
|
|
use Google\Analytics\Data\V1beta\Metric;
|
|
use Google\Analytics\Data\V1beta\RunReportRequest;
|
|
|
|
function sample_run_report($property_id = "YOUR-GA4-PROPERTY-ID") {
|
|
// Make changes here
|
|
$property_id = "436681896";
|
|
|
|
$client = new BetaAnalyticsDataClient();
|
|
|
|
$request = new RunReportRequest([
|
|
'property' => "properties/{$property_id}",
|
|
'metrics' => [new Metric(['name' => 'totalUsers'])], // Fetch the conversion metric
|
|
'dateRanges' => [new DateRange(['startDate' => '2024-01-01', 'endDate' => 'yesterday'])],
|
|
]);
|
|
$response = $client->runReport($request);
|
|
|
|
$total_conversions = 0;
|
|
foreach ($response->getRows() as $row) {
|
|
$total_conversions += intval($row->getMetricValues()[0]->getValue());
|
|
}
|
|
|
|
echo "Total Conversions (yesterday): " . $total_conversions . PHP_EOL;
|
|
}
|
|
|
|
if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'])) {
|
|
sample_run_report();
|
|
}
|
|
|
|
|
|
add_shortcode('ga4_data', 'analytics_report_shortcode');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Add shortcode to fetch GA4 data
|
|
add_shortcode('ga4_data', 'run_analytics_report');
|
|
function run_analytics_report() {
|
|
require 'vendor/autoload.php';
|
|
|
|
|
|
$service_account_key_file_path = "/var/www/html/sigeita/wp-content/plugins/sige-analytics/key.json";
|
|
|
|
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
|
|
|
|
try {
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// CHANGE THIS
|
|
$ga4_property = '436681896';
|
|
|
|
// Set the date range for the last 90 days.
|
|
$start_date = date('Y-m-d', strtotime('-90 days'));
|
|
$end_date = date('Y-m-d');
|
|
$date_range = new \Google\Analytics\Data\V1beta\DateRange(['start_date' => $start_date, 'end_date' => $end_date]);
|
|
$date_ranges = [$date_range];
|
|
|
|
|
|
// Set the dimensions and metrics for the request.
|
|
$dimensions = [new \Google\Analytics\Data\V1beta\Dimension(['name' => 'pagePath'])];
|
|
$metrics = [
|
|
new \Google\Analytics\Data\V1beta\Metric(['name' => 'activeUsers']),
|
|
];
|
|
|
|
$response = $client->runReport([
|
|
'property' => 'properties/' . $ga4_property,
|
|
'dateRanges' => $date_ranges,
|
|
'dimensions' => $dimensions,
|
|
'metrics' => $metrics,
|
|
]);
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
} catch (\Google\ApiCore\ValidationException $e) {
|
|
printf($e);
|
|
}
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
|
|
/*
|
|
Plugin Name: Google Analytics Report Shortcode
|
|
Description: Adds a shortcode to display Google Analytics data.
|
|
|
|
|
|
// Define shortcode handler function
|
|
|
|
function google_analytics_report_shortcode() {
|
|
putenv("GOOGLE_APPLICATION_CREDENTIALS=" . __DIR__ . '/key.json');
|
|
require 'vendor/autoload.php';
|
|
|
|
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
|
|
|
|
$client = new BetaAnalyticsDataClient();
|
|
|
|
$response = $client->runReport([
|
|
'property' => 'properties/[436681896]'
|
|
]);
|
|
|
|
$output = '';
|
|
|
|
foreach ($response->getRows() as $row) {
|
|
foreach ($row->getDimensionValues() as $dimensionValue) {
|
|
$output .= 'Dimension Value: ' . $dimensionValue->getValue() . '<br>';
|
|
}
|
|
}
|
|
|
|
return $output;
|
|
}
|
|
// Register shortcode
|
|
add_shortcode('ga4_data', 'google_analytics_report_shortcode');
|
|
?>
|
|
*/
|
|
|
|
|
|
/**
|
|
* Copyright 2021 Google LLC.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
/* Google Analytics Data API sample quickstart application.
|
|
|
|
This application demonstrates the usage of the Analytics Data API using
|
|
service account credentials.
|
|
|
|
Before you start the application, please review the comments starting with
|
|
"TODO(developer)" and update the code to use the correct values.
|
|
|
|
Usage:
|
|
composer update
|
|
php quickstart.php
|
|
*/
|
|
|
|
|
|
|
|
require 'vendor/autoload.php';
|
|
|
|
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
|
|
use Google\Analytics\Data\V1beta\DateRange;
|
|
use Google\Analytics\Data\V1beta\Dimension;
|
|
use Google\Analytics\Data\V1beta\Metric;
|
|
use Google\Analytics\Data\V1beta\RunReportRequest;
|
|
|
|
// Set the path to the service account key file
|
|
$service_account_key_file_path = __DIR__ . '/key.json';
|
|
|
|
// Function to fetch Google Analytics report
|
|
function google_analytics_report_shortcode($service_account_key_file_path) {
|
|
// TODO: Replace this variable with your Google Analytics 4 property ID before running the sample.
|
|
$property_id = '436681896';
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// Make an API call to get the report
|
|
$request = (new RunReportRequest())
|
|
->setProperty('properties/' . $property_id)
|
|
->setDateRanges([
|
|
new DateRange([
|
|
'start_date' => '2020-03-31',
|
|
'end_date' => 'today',
|
|
]),
|
|
])
|
|
->setDimensions([
|
|
new Dimension(['name' => 'city'])
|
|
])
|
|
->setMetrics([
|
|
new Metric(['name' => 'activeUsers'])
|
|
]);
|
|
|
|
$response = $client->runReport($request);
|
|
|
|
// Print results of the API call
|
|
print 'Report result: ' . PHP_EOL;
|
|
|
|
foreach ($response->getRows() as $row) {
|
|
print $row->getDimensionValues()[0]->getValue()
|
|
. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
|
|
}
|
|
}
|
|
|
|
// Register shortcode
|
|
add_shortcode('ga4_data', function() use ($service_account_key_file_path) {
|
|
google_analytics_report_shortcode($service_account_key_file_path);
|
|
});
|
|
|
|
|
|
function google_analytics_report_totalUsers($service_account_key_file_path) {
|
|
// TODO: Replace this variable with your Google Analytics 4 property ID before running the sample.
|
|
$property_id = '436681896';
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// Make an API call to get the report
|
|
$request = (new RunReportRequest())
|
|
->setProperty('properties/' . $property_id)
|
|
->setDateRanges([
|
|
new DateRange([
|
|
'start_date' => '2020-03-31',
|
|
'end_date' => 'today',
|
|
]),
|
|
])
|
|
->setMetrics([
|
|
new Metric(['name' => 'totalUsers']) // Change 'activeUsers' to 'totalUsers'
|
|
]);
|
|
|
|
$response = $client->runReport($request);
|
|
|
|
// Start PHP session if not already started
|
|
session_start();
|
|
|
|
// Store absolute value in session variable
|
|
$_SESSION['absoluteValue'] = [];
|
|
|
|
// Print absolute value of the metric and store it in session
|
|
foreach ($response->getRows() as $row) {
|
|
$metricValue = $row->getMetricValues()[0]->getValue();
|
|
$absoluteValue = abs($metricValue);
|
|
$_SESSION['absoluteValue'][] = $absoluteValue;
|
|
}
|
|
|
|
// Print the absolute value in HTML as a data attribute
|
|
echo '<div id="absoluteValue" data-value="' . implode(',', $_SESSION['absoluteValue']) . '"></div>';
|
|
}
|
|
|
|
|
|
// Register shortcode
|
|
add_shortcode('ga4_data_totalUsers', function() use ($service_account_key_file_path) {
|
|
google_analytics_report_totalUsers($service_account_key_file_path);
|
|
});
|
|
|
|
function google_analytics_report_screenPageViews($service_account_key_file_path) {
|
|
// TODO: Replace this variable with your Google Analytics 4 property ID before running the sample.
|
|
$property_id = '436681896';
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// Make an API call to get the report
|
|
$request = (new RunReportRequest())
|
|
->setProperty('properties/' . $property_id)
|
|
->setDateRanges([
|
|
new DateRange([
|
|
'start_date' => '2020-03-31',
|
|
'end_date' => 'today',
|
|
]),
|
|
])
|
|
->setMetrics([
|
|
new Metric(['name' => 'screenPageViews']) // Change 'activeUsers' to 'totalUsers'
|
|
]);
|
|
|
|
$response = $client->runReport($request);
|
|
|
|
// Start PHP session if not already started
|
|
|
|
|
|
// Store absolute value in session variable
|
|
$_SESSION['absoluteValuescreenPageViews'] = [];
|
|
|
|
// Print absolute value of the metric and store it in session
|
|
foreach ($response->getRows() as $row) {
|
|
$metricValue = $row->getMetricValues()[0]->getValue();
|
|
$absoluteValue = abs($metricValue);
|
|
$_SESSION['absoluteValuescreenPageViews'][] = $absoluteValue;
|
|
}
|
|
|
|
// Print the absolute value in HTML as a data attribute
|
|
echo '<div id="absoluteValuescreenPageViews" data-value="' . implode(',', $_SESSION['absoluteValuescreenPageViews']) . '"></div>';
|
|
}
|
|
|
|
|
|
// Register shortcode
|
|
add_shortcode('ga4_data_screenPageViews', function() use ($service_account_key_file_path) {
|
|
google_analytics_report_screenPageViews($service_account_key_file_path);
|
|
});
|
|
|
|
|
|
function google_analytics_report_engagementRate($service_account_key_file_path) {
|
|
// TODO: Replace this variable with your Google Analytics 4 property ID before running the sample.
|
|
$property_id = '436681896';
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// Make an API call to get the report
|
|
$request = (new RunReportRequest())
|
|
->setProperty('properties/' . $property_id)
|
|
->setDateRanges([
|
|
new DateRange([
|
|
'start_date' => '2024-01-01',
|
|
'end_date' => 'today',
|
|
]),
|
|
])
|
|
->setMetrics([
|
|
new Metric(['name' => 'engagementRate']) // Change 'activeUsers' to 'totalUsers'
|
|
]);
|
|
|
|
$response = $client->runReport($request);
|
|
|
|
// Start PHP session if not already started
|
|
|
|
|
|
// Store absolute value in session variable
|
|
$_SESSION['absoluteValuesengagementRate'] = [];
|
|
|
|
// Print absolute value of the metric and store it in session
|
|
foreach ($response->getRows() as $row) {
|
|
$metricValue = $row->getMetricValues()[0]->getValue()* 100;
|
|
$absoluteValue = round(abs($metricValue));
|
|
$_SESSION['absoluteValuesengagementRate'][] = $absoluteValue;
|
|
}
|
|
|
|
// Print the absolute value in HTML as a data attribute
|
|
echo '<div id="absoluteValueengagementRate" data-value="' . implode(',', $_SESSION['absoluteValuesengagementRate']) . '"></div>';
|
|
}
|
|
|
|
|
|
// Register shortcode
|
|
add_shortcode('ga4_data_engagementRate', function() use ($service_account_key_file_path) {
|
|
google_analytics_report_engagementRate($service_account_key_file_path);
|
|
});
|
|
|
|
function google_analytics_report_filedownload($service_account_key_file_path) {
|
|
// TODO: Replace this variable with your Google Analytics 4 property ID before running the sample.
|
|
$property_id = '436681896';
|
|
|
|
// Authenticate using a keyfile path
|
|
$client = new BetaAnalyticsDataClient([
|
|
'credentials' => $service_account_key_file_path
|
|
]);
|
|
|
|
// Make an API call to get the report
|
|
$request = (new RunReportRequest())
|
|
->setProperty('properties/' . $property_id)
|
|
->setDimensions([new Dimension(['name' => 'eventName'])])
|
|
->setMetrics([new Metric(['name' => 'eventCount'])])
|
|
->setDateRanges([new DateRange([
|
|
'start_date' => '2024-01-01',
|
|
'end_date' => 'today',
|
|
])
|
|
]);
|
|
|
|
$response = $client->runReport($request);
|
|
|
|
// Start PHP session if not already started
|
|
|
|
// Store absolute value in session variable
|
|
$_SESSION['absoluteValuesfiledownload'] = [];
|
|
|
|
$responseRows = $response->getRows();
|
|
$fifthRow = $responseRows[4]; // Assuming index starts from 0
|
|
$fifthMetricValue = $fifthRow->getMetricValues()[0]->getValue();
|
|
|
|
// Store the fifth metric value in session or use it as needed
|
|
$_SESSION['absoluteValuesfiledownload'][] = $fifthMetricValue;
|
|
// Print absolute value of the metric and store it in session
|
|
|
|
// Print the absolute value in HTML as a data attribute
|
|
|
|
echo '<div id="absoluteValuesfiledownload" data-value="' . implode(',', $_SESSION['absoluteValuesfiledownload']) . '"></div>';
|
|
|
|
|
|
|
|
}
|
|
// Register shortcode
|
|
add_shortcode('ga4_data_filedownload', function() use ($service_account_key_file_path) {
|
|
google_analytics_report_filedownload($service_account_key_file_path);
|
|
});
|
|
|
|
?>
|