WordPressの記事をPythonで更新する方法

ブログ

PythonでWordPress記事を更新する

WordPressサイトを運営していると、既存の記事をプログラムを使って更新したいときがあります。例えば、大量の記事を一括で更新したい場合や、特定の条件に基づいて自動で記事を修正したい場合などです。

ここでは、Pythonを使ってWordPressの記事を更新する方法について解説します。

新規投稿の作成については、以下の記事で解説しています。

必要なライブラリのインストール

PythonでWordPressを操作するためには、python-wordpress-xmlrpcというライブラリを使用します。

ライブラリが存在しない場合は、インストールします。

pip install python-wordpress-xmlrpc

WordPressへの接続設定

WordPressに接続するためには、サイトのURL(‘http://your-wordpress-site.com’の部分)、ユーザー名、パスワードが必要です。これらの情報を使って、Clientオブジェクトを作成します。

from wordpress_xmlrpc import Client

# WordPressのURL、ユーザー名、パスワードを設定
wp = Client('http://your-wordpress-site.com/xmlrpc.php', 'your_username', 'your_password')

投稿記事の更新方法

次に、既存の投稿記事を更新するための関数を作成します。この関数では、以下の要素を更新することができます。

  • タイトル (title)
  • 本文 (body)
  • カテゴリ (categories)
  • タグ (tags)
  • 公開状態 (status)
  • アイキャッチ画像 (eye_catch_img_id)
  • パーマリンク (link_name)
  • メタデータ (meta_data)
  • 公開日 (date)
  • コメント状態 (comment_status)

そのほかの項目を編集したい場合も同じように記述を追加することで実行可能です。
その他の項目については以下の記事で詳細を解説しています。

以下のコードは、指定された投稿記事を更新するための関数です。

from wordpress_xmlrpc.methods.posts import GetPost, EditPost

def update_wp_post(wp, post_id, title=None, body=None, categories=[], tags=[], status=None, eye_catch_img_id=None, link_name=None, meta_data=None, date=None, comment_status=None):
    # 既存の記事を取得
    post = wp.call(GetPost(post_id))

    # タイトルを更新
    if title is not None:
        post.title = title

    # 本文を更新
    if body is not None:
        post.content = body

    # 公開状態を更新
    if status is not None:
        post.post_status = status

    # コメント状態を更新
    if comment_status is not None:
        post.comment_status = comment_status

    # カテゴリとタグを更新
    if tags == [''] or tags == [] and categories != []:
        post.terms_names = {
            "category": categories,
        }
    elif categories != []:
        post.terms_names = {
            "category": categories,
            "post_tag": tags,
        }

    # メタデータを更新
    if meta_data:
        post.custom_fields = [
            {'key': 'the_page_seo_title', 'value': meta_data.get('title', '')},
            {'key': 'the_page_meta_description', 'value': meta_data.get('description', '')},
            {'key': 'the_page_meta_keywords', 'value': meta_data.get('keywords', '')},
        ]

    # パーマリンクを更新
    if link_name is not None:
        post.slug = link_name

    # アイキャッチ画像を更新
    if eye_catch_img_id is not None:
        post.thumbnail = eye_catch_img_id

    # 公開日を更新
    if date is not None:
        post.date = date

    # 記事を更新
    return wp.call(EditPost(post_id, post))

更新の実行

関数を使って記事を更新するには、以下のようにします。例えば、投稿IDが123の記事のタイトルと本文を更新する場合は、次のようにします。

post_id = 123
new_title = "新しいタイトル"
new_body = "こちらが更新された本文です。"

update_wp_post(wp, post_id, title=new_title, body=new_body)

まとめ

この方法を使えば、Pythonから簡単にWordPressの記事を更新することができます。大量の記事を効率的に管理したり、特定の条件に基づいて自動的に記事を更新したりすることが可能です。WordPressを自動化するための強力なツールとして、ぜひ活用してみてください。

コードの詳細

関数定義

def update_wp_post(wp, post_id, title=None, body=None, categories=[], tags=[], status=None, eye_catch_img_id=None, link_name=None, meta_data=None, date=None, comment_status=None):
  • wp: WordPressとの接続を表すClientオブジェクト。
  • post_id: 更新する投稿のID。
  • title, body: 記事のタイトルと本文。Noneの場合、元の内容が保持されます。
  • categories, tags: カテゴリとタグ。リスト形式で渡します。
  • status: 投稿の公開状態(例: ‘publish’, ‘draft’)。
  • eye_catch_img_id: アイキャッチ画像のID。
  • link_name: 投稿のパーマリンク(スラッグ)。
  • meta_data: SEO関連のメタデータ。辞書形式でタイトル、説明、キーワードを含みます。
  • date: 投稿の公開日。
  • comment_status: コメントの許可設定(例: ‘open’, ‘closed’)。

既存の記事の取得

post = wp.call(GetPost(post_id))
  • 指定したpost_idの投稿記事を取得します。このpostオブジェクトには記事の現在の状態が含まれています。

タイトル、本文、公開状態、コメントステータスの更新

if title is not None:
    post.title = title
  • titleが指定されている場合、記事のタイトルを新しいタイトルに更新します。
if body is not None:
    post.content = body
  • bodyが指定されている場合、記事の本文を新しい内容に更新します。
if status is not None:
    post.post_status = status
  • statusが指定されている場合、記事の公開状態を更新します。
if comment_status is not None:
    post.comment_status = comment_status
  • comment_statusが指定されている場合、記事のコメント許可設定を更新します。

カテゴリとタグの更新

if tags == [''] or tags == [] and categories != []:
    post.terms_names = {
        "category": categories,
    }
elif categories != []:
    post.terms_names = {
        "category": categories,
        "post_tag": tags,
    }
  • カテゴリとタグの更新を行います。タグが指定されていない場合はカテゴリのみを更新し、両方が指定されている場合は両方を更新します。

メタデータの更新

if meta_data:
    post.custom_fields = [
        {'key': 'the_page_seo_title', 'value': meta_data.get('title', '')},
        {'key': 'the_page_meta_description', 'value': meta_data.get('description', '')},
        {'key': 'the_page_meta_keywords', 'value': meta_data.get('keywords', '')},
    ]
  • SEOに関連するメタデータを更新します。辞書形式で渡されたmeta_dataの値を使って、カスタムフィールドを設定します。

パーマリンクの更新

if link_name is not None:
    post.slug = link_name
  • link_nameが指定されている場合、記事のパーマリンク(スラッグ)を更新します。

アイキャッチ画像の更新

if eye_catch_img_id is not None:
    post.thumbnail = eye_catch_img_id
  • eye_catch_img_idが指定されている場合、アイキャッチ画像を更新します。

公開日の更新

if date is not None:
    post.date = date
  • dateが指定されている場合、記事の公開日を更新します。

記事の更新

return wp.call(EditPost(post_id, post))
  • 最後に、EditPostメソッドを呼び出して、すべての変更をWordPressに反映させます。このメソッドは、更新が成功するとTrueを返します。

コメント

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