CocoonでmetaタグをPythonから操作する方法

WordPress

WordPressサイトをCocoonテーマで運営している場合、投稿やページのメタタグをPythonを使って設定することができます。この記事では、python-wordpress-xmlrpcライブラリを利用して、Cocoonテーマに最適化されたメタタグを設定する方法を紹介します。

準備

まず、Python環境に必要なライブラリをインストールします。以下のコマンドでpython-wordpress-xmlrpcをインストールしてください。

pip install python-wordpress-xmlrpc

コード全体

以下のPythonスクリプトは、WordPressサイトに投稿を作成し、Cocoonテーマで使用するメタタグをカスタムフィールドとして設定するものです。

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost

# 接続情報の設定
url = "https://example.com/xmlrpc.php"
username = "your_username"
password = "your_password"

# クライアントの作成
client = Client(url, username, password)

# 新しい投稿の作成
post = WordPressPost()
post.title = 'メタタグテスト投稿'
post.content = 'メタタグを設定してみます'
post.terms_names = {
    'post_tag': ['tag1', 'tag2'],
    'category': ['Category1']
}
post.custom_fields = [
    {'key': 'the_page_seo_title', 'value': 'メタタグタイトル'},
    {'key': 'the_page_meta_description', 'value': 'メタタグデスクリプション'},
    {'key': 'the_page_meta_keywords', 'value': 'キーワード1, キーワード2'},
]

# 投稿のパーマリンク設定
post.slug = 'test-post-with-meta-tags'

# 投稿のステータス設定
post.post_status = 'draft'

# 投稿を送信して作成
try:
    post_id = client.call(NewPost(post))
    print(f"Post created with ID: {post_id}")
except Exception as e:
    print(f"An error occurred: {e}")

コードの解説

  1. クライアントの作成:
    Client(url, username, password)を使用して、WordPressサイトに接続します。

  2. 新しい投稿の作成:
    WordPressPostオブジェクトを作成し、投稿タイトル、内容、カテゴリ、タグを設定します。

  3. メタタグの設定:
    custom_fields属性を使ってメタタグを設定します。Cocoonテーマに特有のカスタムフィールドthe_page_seo_titlethe_page_meta_descriptionthe_page_meta_keywordsを使用しています。

  4. パーマリンクの設定:
    slug属性で投稿のパーマリンクを設定します。

  5. 投稿のステータス設定:
    post_status'publish'に設定して、投稿を公開状態にします。

  6. 投稿の送信:
    client.call(NewPost(post))で投稿をWordPressサイトに送信します。

検証結果

実際に実行して記事をブラウザの検証機能で確認しました。
headerの部分にきちんとコードに記入したメタタグの内容が反映されていました!

メタタグ設定のスクリーンショット
メタタグ設定のスクリーンショット

まとめ

CocoonテーマでメタタグをPythonを使って設定する方法を紹介しました。python-wordpress-xmlrpcライブラリを活用することで、プログラムから直接WordPressにメタタグを設定できるようになります。この方法を使えば、大量の投稿やページに対しても効率的にメタタグを管理できます。

タイトルとURLをコピーしました