2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-03-24

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);
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?