Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@horikeso

WP REST API v2でカスタムフィールドを含む投稿を行う

Reference

環境はWPの公式イメージから作成

WP REST API v2のベーシック認証がうまくいかなかった(こちらも試した)のでとりあえずJWTのプラグインを使った。

JWT Authentication for WP REST APIの設定

.htaccess
# BEGIN WordPress
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
# END WordPress

wp-config.phpに以下を先頭に追加

※末尾だとJWT is not configurated properly, please contact the admin

wp-config.php
/** JWT Authentication for WP REST API */
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);

your-top-secret-keyは設定する

トークン取得

/wp-json/jwt-auth/v1/token
リクエストボディ
{
  "username" : "admin",
  "password" : "admin"
}

投稿

/wp-json/wp/v2/posts
リクエストヘッダ
Authorization: Bearer <トークン>
リクエストボディ
{
  "title" : "WP REST API v2",
  "status" : "publish",
  "content" : "content",
  "categories" : "1,2",
  "tags" : "3,4"
  "meta" : {
    "custom_field_name" : "value"
  }
}

metaは今のところ設定しないと投稿時に登録できない様子
hookでpostsにmetaを追加する方法で対応する

カテゴリーとタグはドキュメントではarrayになっているけどstringでした・・・
カテゴリIDの確認は/wp-json/wp/v2/categories
タグIDの確認は/wp-json/wp/v2/tags

Post Types

今回は投稿なのでrest_insert_postにした以下の設定を追記

wp-content\themes\XXXXXX\functions.php
add_action('rest_insert_post', function (\WP_Post $post, $request, $creating)
{
    $metas = $request->get_param('meta');

    if (is_array($metas))
    {
        foreach ($metas as $name => $value)
        {
            update_post_meta($post->ID, $name, $value);
        }
    }
}, 10, 3);
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?