MENU

WordPress REST APIで記事を投稿しカスタムフィールドを設定する方法

WordPress REST APIを使用して記事を投稿すると同時に、カスタムフィールドを設定することができます。本記事では、Pythonを使用してREST API経由で記事を作成し、カスタムフィールドを設定または更新する手順を紹介します。


目次

準備

アプリパスワードを取得します。


functions.phpに以下のコードを追加し、カスタムフィールドをREST APIで操作可能にします。

function register_custom_meta_fields() {
    register_post_meta('post', 'custom_field_key_1', array(
        'type'         => 'string',
        'single'       => true,
        'show_in_rest' => true,
    ));
    register_post_meta('post', 'custom_field_key_2', array(
        'type'         => 'number',
        'single'       => true,
        'show_in_rest' => true,
    ));
}
add_action('init', 'register_custom_meta_fields');

Pythonで記事を投稿しカスタムフィールドを設定する

以下は、Pythonを使用してWordPressのREST APIで記事を作成し、カスタムフィールドを設定するコードです。

コード例

import requests
from requests.auth import HTTPBasicAuth

# WordPressの設定
WORDPRESS_URL = "https://your-wordpress-site.com/wp-json/wp/v2/posts"
USERNAME = "your-username"
APP_PASSWORD = "your-app-password"

def create_post(title, content, custom_fields):
    """
    WordPress REST APIを使用して記事を作成し、カスタムフィールドを設定
    """
    headers = {"Content-Type": "application/json"}
    data = {
        "title": title,
        "content": content,
        "status": "publish",
        "meta": custom_fields,  # カスタムフィールド
    }

    response = requests.post(
        WORDPRESS_URL,
        json=data,
        auth=HTTPBasicAuth(USERNAME, APP_PASSWORD),
        headers=headers,
    )

    if response.status_code == 201:
        print(f"投稿が成功しました: {title}")
        print(response.json())  # 応答データを表示
    else:
        print(f"投稿に失敗しました: {response.status_code}")
        print(response.text)

# サンプルデータ
posts = [
    {
        "title": "サンプル投稿 1",
        "content": "<p>この投稿はREST APIで作成されました。</p>",
        "custom_fields": {
            "custom_field_key_1": "サンプル値1",
            "custom_field_key_2": 100,
        },
    },
    {
        "title": "サンプル投稿 2",
        "content": "<p>こちらもREST APIで作成されました。</p>",
        "custom_fields": {
            "custom_field_key_1": "サンプル値2",
            "custom_field_key_2": 200,
        },
    },
]

# 投稿をループして作成
for post in posts:
    create_post(post["title"], post["content"], post["custom_fields"])

詳細な解説

カスタムフィールドの設定

  • 上記コードの custom_fields は、REST APIの meta に渡されます。
  • WordPressに登録されているカスタムフィールド(functions.php で登録)だけが受け付けられます。
  • 未登録のカスタムフィールドを送信するとエラーになります。

既存記事のカスタムフィールドを更新する

既存の記事のカスタムフィールドを更新するには、PATCH メソッドを使用します。

コード例

def update_post(post_id, custom_fields):
    """
    WordPress REST APIを使用して既存記事のカスタムフィールドを更新
    """
    url = f"{WORDPRESS_URL}/{post_id}"
    headers = {"Content-Type": "application/json"}
    data = {
        "meta": custom_fields,  # 更新するカスタムフィールド
    }

    response = requests.patch(
        url,
        json=data,
        auth=HTTPBasicAuth(USERNAME, APP_PASSWORD),
        headers=headers,
    )

    if response.status_code == 200:
        print(f"投稿 (ID: {post_id}) が更新されました。")
        print(response.json())
    else:
        print(f"更新に失敗しました: {response.status_code}")
        print(response.text)

# サンプル更新データ
update_post(123, {
    "custom_field_key_1": "更新された値",
    "custom_field_key_2": 300,
})

エラーハンドリング

  1. 認証エラー
    • 正しい認証情報(ユーザー名とアプリパスワード)が必要です。
    • エラー例: { "code": "rest_cannot_create", "message": "Sorry, you are not allowed to create posts as this user.", "data": { "status": 403 } }
  2. カスタムフィールド未登録エラー
    • カスタムフィールドが register_post_meta で登録されていない場合はエラーになります。
    • エラー例: { "code": "rest_invalid_param", "message": "Invalid parameter(s): meta", "data": { "status": 400 } }

まとめ

  1. カスタムフィールドの登録
    • functions.phpregister_post_meta を記述してREST APIで操作可能にする。
  2. 記事の作成
    • POST メソッドで記事を作成し、同時にカスタムフィールドを設定。
  3. 記事の更新
    • PATCH メソッドでカスタムフィールドを更新可能。

上記の方法で、REST APIを通じてWordPressの記事とカスタムフィールドを簡単に操作できます。

目次