LoginSignup
32
25

More than 5 years have passed since last update.

WP-APIのスキーマにカスタムフィールドを追加する

Last updated at Posted at 2016-06-14

WP-APIでは、デフォルトではカスタムフィールドは出力されません。

なぜかというとサードパーティのプラグインがいつの間にかセキュリティ的に重要な情報を出力している可能性があるからなんですよね。

ただし、カスタムフィールドを出力するプラグインを作るのはそれほど難しくありません。

<?php
/**
 * Plugin Name: Add Meta to REST-API
 * Author: Takayuki Miyauchi
 * Description: Example plugin that adds post meta to rest-api.
 */

add_action( 'rest_api_init',  function() {
    register_rest_field(
        'post',        // post type
        'post_meta',   // rest-apiに追加するキー
        array(
            'get_callback'  => function(  $object, $field_name, $request  ) {
                // 出力したいカスタムフィールドのキーをここで定義
                $meta_fields = array(
                    'color',
                    'price',
                );
                $meta = array();
                foreach ( $meta_fields as $field ) {
                    // バリデーションを一切してないので注意
                    $meta[ $field ] = get_post_meta( $object[ 'id' ], $field, true );
                }
                return $meta;
            },
            'update_callback' => null,
            'schema'          => null,
        )
    );
} );

上のコードの中の以下の部分で出力したいカスタムフィールドを配列で指定しています。

$meta_fields = array(
    'color',
    'price',
);

これをプラグインとして有効化してREST APIのエンドポイントにアクセスすると以下のような感じでJSONが出力されていることが確認できると思います。

"post_meta": {
  "color": "Red",
  "price": "123000"
},

Pawというアプリで見るとこんな感じ。

32
25
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
32
25