Googleサーチコンソールでサイトマップを送っても、なかなか巡回されず、インデックス登録されないことは少なくないと思います。
それに加えて記事が増えてきて、GoogleサーチコンソールでURLを1ページずつポチポチコピーしてインデックス登録をしていくのも大変ですよね。
そんなときに役立つのが、「WordPress REST API」と「Indexing API」です。
指定したWordPressサイトから全記事のURLを取得してインデックス登録をリクエストする
プログラムコードを用意しましたので良ければ使ってみてください。
import json
import requests
import time
from google.oauth2 import service_account
from google.auth.transport.requests import Request
# サービスアカウントキーファイルとサイトのURLを設定
service_account_file = '【サービスアカウントキーファイル】.json'
site_url = "【あなたのサイトurl】/"
wp_api_url = f"{site_url}wp-json/wp/v2/posts"
ArticleNumPerPage = 1
# 認証情報を取得
credentials = service_account.Credentials.from_service_account_file(service_account_file)
# 必要なスコープを指定
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/indexing'])
# アクセストークンを取得
auth_req = Request()
scoped_credentials.refresh(auth_req)
access_token = scoped_credentials.token
# アクセストークンをヘッダーに設定
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
# WordPress REST APIから全記事を取得
urls = []
response = requests.get(wp_api_url, params={"per_page": ArticleNumPerPage})
if response.status_code == 200:
PostsHeadResult = response.headers
MaxPage = int(PostsHeadResult['X-WP-TotalPages'])
ArticleList = []
for i in range(1, MaxPage + 1):
PostsGetParameters = {
'page' : i,
'per_page' : ArticleNumPerPage,
'order' : 'desc'
}
PostsGetResponse = requests.get(wp_api_url, params = PostsGetParameters)
if PostsGetResponse.status_code == 200:
PostsGetResult = json.loads(PostsGetResponse.text)
ArticleList.extend(PostsGetResult)
else:
print(f"Error occurred on page {i} with status code {PostsGetResponse.status_code}. Message: {PostsGetResponse.text}")
try:
urls.extend([ArticleItem["link"] for ArticleItem in ArticleList])
except TypeError:
print(f"TypeError occurred for the following data: {ArticleItem}")
with open('registered_urls.txt', 'a+') as f:
f.seek(0)
registered_urls = f.read().splitlines()
count = 0
for url in urls:
if url in registered_urls:
continue
if count >= 2000:
print("1日のリクエスト制限に達しました。")
break
# APIリクエストのURLを作成
api_url = "https://indexing.googleapis.com/v3/urlNotifications:publish"
# リクエストのボディを作成
body = json.dumps({
"url": url,
"type": "URL_UPDATED",
})
# APIリクエストを送信
response = requests.post(api_url, headers=headers, data=body)
print(response.json())
f.write(url + '\n')
count += 1
# 1分間のリクエスト上限を守るための待機時間
time.sleep(0.1)
