このサイトのアクセスランキングをAnalyticsデータを参照して実装したので紹介します。
アクセスランキングはプラグインを使うと簡単に実装出来るのですが、あまりプラグインに依存したくなかったのとプラグインをインストールすることによりデータベースのテーブルが作成されるのがあまり良い方法ではないと思ったので、GoogleのAnalytics APIで実装しました。
参考までにプラグインで対応する場合は、以下を使うことで実現出来ます。
WordPress Popular PostsやWP-PostViewsを使うことで簡単に実装出来ますが、カスタマイズが難しかったりと色々とやっかいな問題が発生しそうなのでGoogle AnalyticsのAPIを使うことをお勧めします。
Google Analytics APIの参考になるドキュメント↓↓
https://developers.google.com/analytics/
目次
1) 実現したいこと
2) Google API Managerで登録作業
3) Google Analyticsにユーザー登録
4) ライブラリを使ってAnalyticsからデータを取得
5) functions.phpファイルで表示に必要な関数を作成
6) テンプレートで呼び出す
実現したいこと
前日から30日以内の合計PV数が多い順5件の情報を取得して、「Featured Image」、「タイトル」、「投稿日付」、「記事リンク」を取得する。
おおまかな流れは、
1) AnalyticsからURLとページビュー数を多い順に○○件取得します。(ここでは30件取得します。)
2) Analyticsから取得したURLを元に、Wordpressの記事情報を取得してセットします。
3) 2でセットした情報をテンプレートでループして表示します。
※記事が持っている情報(投稿者やコメントや本文など)は全て取得できます。
以下が完成イメージです。
Google API Managerで登録作業
Google API Managaerへアクセスして、Credentialsの作成と秘密鍵(Json形式)を取得します。
Google API Managaer
https://console.developers.google.com/
以前の記事で登録方法を紹介しているので参考にしてみてください。
:: Google APIでアクセス実績を取得し、crontabでcsvファイルを自動生成する方法 php
Google API Managaerの画面が以前と変わっている部分がありますが、基本的には変わりはありません。
プロジェクト作成
以下からプロジェクトを作成してください。すでにプロジェクトを持っていればそちらを使ってもらってOKです。
Credentialsの作成
Create credentialsから Service account keyを作成します。
Service account Keyを作成
アカウント名は任意の名前でOKです。秘密鍵のタイプはJSONを選んでください。「作成」ボタンを押すと、ファイルがダウンロードされます。これは後で使用します。
最後に、以下の2つをメモしておきます
- Client ID:API Manager –> Credentials –> から確認できます。(形式:***********-********************************.apps.googleusercontent.com)
- Email address:Permissions –> Service accountsから確認できます。(形式:service-account@grooving-earth-****.iam.gserviceaccount.com)
Google Developers Consoleの設定は以上です。
もしつまずいたらGoogleのドキュメントも参考にしてみてください。
https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php
Google Analyticsにユーザー登録
Google Analytics側の管理画面で先ほど作成したアカウントからのアクセスを許可します。
アカウントのアクセス許可を「表示と分析」とし、
以上で、Google Analyticsの設定は終了です。
ライブラリを使ってAnalyticsからデータを取得
2017年1月22日時点では、「Google クライアント ライブラリ」の最新版はv2.1.1ですが、今回はv2.0.0を使用します。
以下のURLよりGoogleが提供している「Google クライアント ライブラリ」をダウンロードします。
https://github.com/google/google-api-php-client/releases/download/v2.0.0/google-api-php-client-2.0.0.zip
「Google クライアント ライブラリ」のリリースヒストリーは以下から確認できます。
https://github.com/google/google-api-php-client/releases
ダウンロードしたら、wordpressのテーマフォルダに「modules」フォルダを作成、さらにその中に「gapi」フォルダを作成しました。
以下のようなディレクトリになるかと思います。
wp-content/themes/テーマ名/modules/gapi/ここにダウンロードしたファイルを格納します。
ダウンロードしたファイルを格納したフォルダは以下のようになります。
composer経由でダウンロードしていない場合は、composer.jsonとcomposer.lockはありません。
get-access-ranking.phpの中身は以下になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; $analytics = initializeAnalytics(); $profile = getFirstProfileId($analytics); $results = getMonthlyRanking($analytics, $profile); function initializeAnalytics() { // Creates and returns the Analytics Reporting service object. // 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 = __DIR__ . '/**************.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_Analytics($client); return $analytics; } function getFirstProfileId($analytics) { // Get the user's first view (profile) ID. // Get the list of accounts for the authorized user. $accounts = $analytics->management_accounts->listManagementAccounts(); if (count($accounts->getItems()) > 0) { $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); // Get the list of properties for the authorized user. $properties = $analytics->management_webproperties ->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0) { $items = $properties->getItems(); $firstPropertyId = $items[0]->getId(); // Get the list of views (profiles) for the authorized user. $profiles = $analytics->management_profiles ->listManagementProfiles($firstAccountId, $firstPropertyId); if (count($profiles->getItems()) > 0) { $items = $profiles->getItems(); // Return the first view (profile) ID. return $items[0]->getId(); } else { throw new Exception('No views (profiles) found for this user.'); } } else { throw new Exception('No properties found for this user.'); } } else { throw new Exception('No accounts found for this user.'); } } function getMonthlyRanking($analytics, $profileId) { $results = $analytics->data_ga->get( 'ga:' . $profileId, '30daysAgo', 'yesterday', 'ga:Pageviews', array( 'dimensions' => 'ga:pagePath', // 副指標 'sort' => '-ga:Pageviews', // - を付けると降順ソート 'max-results' => 30, // 取得件数 ) ); // 取得したデータから必要な部分を抽出 $data = $results->rows; // 配列で取得したデータをループで回してランキングに $ranking = array(); foreach ($data as $key => $row) { $ranking[] = array('url'=>$row[0], 'pv'=>$row[1]); } return $ranking; } |
$KEY_FILE_LOCATION = __DIR__ . ‘/**************.json’;はGoogle API Managerで取得したJSONファイルを読み込みます。
function getMonthlyRankingの$results変数に取得するデータや期間を指定しています。
試しにvar_dumpしてデータが正しく取れているか確認してみてください。
$ranking変数をvar_dumpすれば取得できます。
functions.phpファイルで表示に必要な関数を作成
wordpressのfunctions.php内に以下のコードを貼り付けます。
やっていることは、
- get-access-ranking.phpを呼び出す
- $resultsを$gapiDataに格納
- post_typeがpostで、且つ公開済みの記事を対象に5件の情報をforeach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Get Access Ranking using Google API * @return url, pageview */ function AccessRanking() { require_once(TEMPLATEPATH.'/modules/gapi/get-access-ranking.php'); // get-access-ranking.phpでセットしたAPIデータを格納 $gapiData = $results; $ranking_posts = array(); $i = 0; foreach( $gapiData as $result_each ){ $path = $result_each['url']; if( url_to_postid($path) != 0 || $path != '/' ){ $data = get_post( url_to_postid( $path ) ); if( !empty($data) && $data->post_type === 'post' && $data->post_status === 'publish' ){ $ranking_posts[] = get_post(url_to_postid($path)); $i++; if( $i == 5) break; } } } return $ranking_posts; } |
*if( $i == 5) break;の数字を変えると取得する件数を変えることが出来ます。
テンプレートで呼び出す
最後に、returnしていた$ranking_postsをテンプレート側で呼び込みます。
以下のソースコードです。
- $post_id = $v->ID; <- 記事IDを取得
- $post_url = get_permalink($post_id); <- 記事IDからページURLを取得
- $post_title = $v->post_title; <- 記事タイトルを取得
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php foreach(AccessRanking($ranking_posts) as $r => $v): if($k!==0): $post_id = $v->ID; $post_url = get_permalink($post_id); $post_title = $v->post_title; ?> <div class="row"> <div class="col-md-12 mb10"> <article class="blog-list_related"> <div class="row"> <div class="col-xs-4"> <figure class=""><a href="<?php echo $post_url;?>"><?php echo get_the_post_thumbnail( $post_id, 'thumbnail', array('class' => 'img-responsive')); ?></a></figure> </div> <div class="col-xs-8 pl0"> <p class="post_title"><a href="<?php echo $post_url;?>"><?php echo $post_title; ?></a></p> <p class="desc"><time><i class="fa fa-calendar"></i> <?php echo get_the_date('Y/m/d',$post_id); ?></time></p> </div><!-- /.col --> </div><!-- /.row --> </article> </div><!-- /.col --> </div><!-- /.row --> <?php else: ?> <!-- 記事がない場合の処理 --> <div class="col-md-12"> <p>No Entry</p> </div><!-- /.col --> <?php endif; ?> <?php endforeach; ?> |
以上で無事にGoogle Analyticsの数字を元にしたランキングを取得出来ました。
お疲れ様でした。
LEAVE A REPLY