REST API
以前は、プラグインが必要だったREST APIですが、現行のWordPress5のcoreには、初めからREST APIが入っているようです。
今回、繰り替えしのフィールドが必要だったため、カスタムフィールドを登録するプラグインはSmart Custom Fieldを使用します。
カスタム投稿タイプとカスタムフィールドをREST APIに出力
カスタム投稿タイプをREST APIに出力するには、カスタム投稿タイプ作成時にREST APIに出力する設定が必要です。
function create_post_type() {
$supports = [
'title', // title
'editor', // editor
];
register_post_type( 'fruits', // 例:果物の場合
array(
'label' => '果物',
'public' => true,
'has_archive' => false,
'menu_position' => 7,
'supports' => $supports,
'show_in_rest' => true, //rest api での取得有効にする
'rest_base' => 'fruits' // rest api での取得名 /wp-json/wp/v2/fruits
)
);
}
add_action( 'init', 'create_post_type' );
REST APIの結果を確認してみましょう。
https://your-domain.com/wp-json/wp/v2/fruits
次にSmart Custom Fieldの値をREST APIに出力する設定を行います。
仮にSmart Custom Fieldに設定した名前が以下とします。
| fruits_color | テキストが入ります。 |
| fruits_image | idが入ります。 |
functions.phpに以下のコードを入力します。
// rest apiにカスタムフィールドを出力
add_action( 'rest_api_init', 'slug_register_fruits' );
function slug_register_fruits() {
register_rest_field(
'fruits', //フィールドを追加したいcustom投稿タイプを指定(先ほど登録したカスタム投稿タイプslugを指定)
'fruits_meta', // rest-apiに追加するキー
array(
'get_callback' => function( $object, $field_name, $request ) {
// 出力したいカスタムフィールドのキーをここで定義
$meta_fields = array(
'fruits_color',
'fruits_image',
);
$meta = array();
foreach ( $meta_fields as $field ) {
// バリデーションを一切してないので注意
$meta[ $field ] = get_post_meta( $object['id'], $field, false ); // 第3引数はfalse、Smart Custom Fieldの繰り替えし機能を使うため
}
return $meta;
},
'update_callback' => null,
'schema' => null,
)
);
}
ここで注意して欲しいのが17行目のget_post_meta関数の第3引数です。
Smart Custom Fieldの繰り返しの機能を利用すると、繰り返されたグループの値は、カスタムフィールドに配列で格納されます。
そのため、第3引数にfalseを渡して、値を配列として受け取ります。
第3引数がtrueだと、繰り返されたグループの値が取得できません。
REST APIの出力結果を確認してみましょう。
カスタムフィールドの値が出力されているのが確認できると思います。
https://your-domain.com/wp-json/wp/v2/fruits
参考
wordpress rest-apiでカスタムフィールドを出力する際に処理結果を整形したい
https://qiita.com/kinshist/items/cd9f74af7db7c80746a1