WP Rest APIでカスタムフィールドの値を取得・更新をしよう!
今回は、カスタムフィールドの値を取得します。
ACF to Rest APIのダウンロード
プラグインであるACF to Rest APIを使います。 まずは、プラグインから検索をして、ACF to Rest APIを導入してください。
ACF to Rest APIの設定
wp_config.phpに以下を追加します。
define( 'ACF_TO_REST_API_REQUEST_VERSION', 3 );
次にテーマフォルダの中にあるfunction.phpに以下を追記します。
// Enable the option show in rest add_filter( 'acf/rest_api/field_settings/show_in_rest', '__return_true' ); // Enable the option edit in rest add_filter( 'acf/rest_api/field_settings/edit_in_rest', '__return_true' );
カスタムフィールドの作成
以下のようにカスタムフィールドを作成します。 この時、RESTAPIを使えるようにする必要があります。
Pythonコード
値の取得
実際にPythonで投稿のカスタムフィールドの値を取得するには、
import requests res = requests.get('http://localhost/wordpress/wp-json/wp/custom/posts_by_users')
のようにします。
値の更新
更新する場合は以下のようにします。 fields["text_item"]のようにしてフィールの値を更新できます。 更新に関しては、認証が必要になるので、認証のpasswordをheaderに持たせます。
auth_str = "ユーザー名:パスワード" auth_base64_bytes = base64.b64encode(auth_str.encode(encoding='utf-8')) auth = auth_base64_bytes.decode(encoding='utf-8') headers = { 'Authorization': 'Basic ' + auth } data = { "fields[text_item]":["編集しました"], "fields[bool_item]":["true"], } res = requests.post('http://localhost/wordpress/wp-json/acf/v3/posts/93', headers=headers, data = data)
これを実行すると値の更新や読み取りが可能です。