Skip to content

Instantly share code, notes, and snippets.

@matthewmcvickar
Last active February 15, 2023 18:53
Show Gist options
  • Save matthewmcvickar/f46282120ac2ccc0b526d128035df839 to your computer and use it in GitHub Desktop.
Save matthewmcvickar/f46282120ac2ccc0b526d128035df839 to your computer and use it in GitHub Desktop.
Using Google Analytics to Get the Most Popular WordPress Pages

This is a set of PHP scripts to fetch the most-viewed pages from a Google Analytics property.

You will need to set up API access for this project in the Google Cloud Platform Console and create an authorization JSON file.

{
"require": {
"google/apiclient": "^2.7"
},
"scripts": {
"post-update-cmd": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": [
"Analytics"
]
}
}
<?php
// Load the Google API PHP Client library.
require_once( __DIR__ . '/../vendor/autoload.php' );
// Establish a client connection with the service account.
function establish_client_connection() {
$client = new Google_Client();
$client->setAuthConfig( __DIR__ . '/google-api-service-account-credentials-TODO.json' );
$client->setScopes( ['https://www.googleapis.com/auth/analytics.readonly'] );
$analytics = new Google_Service_Analytics( $client );
if ( empty( $client ) || empty( $analytics ) ) {
throw new Exception( 'Could not connect to Google Analytics API.' );
}
return $analytics;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment