HOME / BLOG
BLOG

WordPressでSearch Console APIを使って検索順位を取得する方法

デフォルト画像

Search Consoleの検索クエリや平均掲載順位をWordPress側で見られると、記事改善の優先順位を決めやすくなります。どの記事が何のキーワードで表示され、何位くらいにいるのかを、管理画面や自作ダッシュボードで確認できるからです。

この記事では、Search Console APIのSearch Analyticsを使って、特定ページの検索語句、クリック数、表示回数、CTR、平均掲載順位を取得する方法をまとめます。

取得できる主なデータ

  • query: 検索語句
  • page: 対象URL
  • clicks: クリック数
  • impressions: 表示回数
  • ctr: クリック率
  • position: 平均掲載順位

ComposerでGoogle API Clientを入れる

composer require google/apiclient:^2.0

Search Console APIで順位を取得するPHP

個人サイトのWordPressで扱う場合、OAuthのrefresh tokenを保存してaccess tokenを再発行する構成が使いやすいです。サービスアカウントを使う場合も、Search Console側で対象プロパティに権限を付ける必要があります。

<?php
use Google\Client;
use Google\Service\SearchConsole;
use Google\Service\SearchConsole\SearchAnalyticsQueryRequest;

function nines_get_search_console_queries(string $page_url, int $days = 28): array
{
    $client = new Client();
    $client->setAuthConfig('/home/your-user/secure/google-oauth-client.json');
    $client->setAccessType('offline');
    $client->setScopes([SearchConsole::WEBMASTERS_READONLY]);

    // 実運用では、保存済みrefresh tokenからaccess tokenを再発行する。
    $client->fetchAccessTokenWithRefreshToken(get_option('nines_gsc_refresh_token'));

    $service = new SearchConsole($client);

    $request = new SearchAnalyticsQueryRequest();
    $request->setStartDate(date('Y-m-d', strtotime("-{$days} days")));
    $request->setEndDate(date('Y-m-d'));
    $request->setDimensions(['query']);
    $request->setRowLimit(20);
    $request->setDimensionFilterGroups([[
        'filters' => [[
            'dimension' => 'page',
            'operator' => 'equals',
            'expression' => $page_url,
        ]],
    ]]);

    $response = $service->searchanalytics->query('https://example.com/', $request);

    return array_map(function ($row) {
        return [
            'query' => $row->getKeys()[0] ?? '',
            'clicks' => $row->getClicks(),
            'impressions' => $row->getImpressions(),
            'ctr' => $row->getCtr(),
            'position' => $row->getPosition(),
        ];
    }, $response->getRows() ?: []);
}

テーマで表として表示する

平均掲載順位は小数で返るので、画面では1桁程度に丸めると読みやすくなります。CTRは0から1の数値なので、100を掛けてパーセント表示にします。

<?php $queries = nines_get_search_console_queries(get_permalink(), 28); ?>

<table class="search-console-table">
  <thead>
    <tr>
      <th>検索語句</th>
      <th>クリック</th>
      <th>表示回数</th>
      <th>CTR</th>
      <th>平均掲載順位</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($queries as $query) : ?>
      <tr>
        <td><?php echo esc_html($query['query']); ?></td>
        <td><?php echo esc_html($query['clicks']); ?></td>
        <td><?php echo esc_html($query['impressions']); ?></td>
        <td><?php echo esc_html(round($query['ctr'] * 100, 1)); ?>%</td>
        <td><?php echo esc_html(round($query['position'], 1)); ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

記事改善で見るポイント

  • 表示回数が多く、順位が8位から20位の記事は改善余地が大きい
  • 順位は高いのにCTRが低い記事はタイトルとメタディスクリプションを見直す
  • 想定外の検索語句で表示されている記事は、見出しを追加して受け皿を作る
  • クリックがある検索語句は、関連記事や内部リンクで伸ばす

よくある失敗

  • Search Consoleに登録しているURLとAPIに渡すsiteUrlが一致していない
  • httpとhttps、wwwありなしを混同する
  • 平均掲載順位を「確定順位」として扱ってしまう
  • 毎回APIを叩いて表示が遅くなる

参考資料

まとめ

Search Console APIをWordPressに組み込むと、記事の検索順位を日々の編集作業に直結させられます。まずは記事URL単位で検索語句と順位を見るところから始めると、リライト対象をかなり選びやすくなります。