Wordpress REST APIでpost_meta(カスタムフィールド)も同時に投稿する


投稿側の機能

post.php
function post_article($status,$slug,$title,$category_ids,$tag_ids,$image,$date){

    $WP_URL = 'http://example.com/wp-json/wp/v2/cutom_post_type'; 
    $WP_USERNAME = 'user';
    $WP_PASSWORD = 'pw';

    //記事投稿
    $response = wp_remote_post($WP_URL, array(
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode($WP_USERNAME.':'.$WP_PASSWORD),
            'Content-Type: application/json'
        ),
        'body' => array(
              "status"=> $status,
              "slug"=> $slug,
              "title"=> $title,
              "date"=> $date,
              "categories"=> $category_ids,
              "tags"=> $tag_ids,
              "featured_media"=>$media_id,
              "post_meta"=>array(    // functions.php側で「rest-apiに追加するキー」に設定したもの
                 //ここ
                'custom_field1'=>"a",
                'custom_field2'=>"b"
              )
        )
    ) );
}

functions.php側にもpost_metaをAPIで利用可能にする拡張が必要

functions.php
function rest_post_meta(){
  register_rest_field(
    'custom_post_type',        // post type
    'post_meta',               // rest-apiに追加するキー
    array(
      'get_callback'  => function(  $object, $field_name, $request  ) {
        $meta_fields = array(
            'custom_field1',   
            'custom_field2'
            );
            $meta = array();
            foreach ( $meta_fields as $field ) {
                $meta[ $field ] = get_post_meta( $object[ 'id' ], $field, true );
            }
            return $meta;
        },
        'update_callback' => function(  $value, $post, $field_name) {
            if (!$value) {return;}
            foreach($value as $key => $data){
                if(is_array($data)){
                    foreach($data as $record){
                        add_post_meta($post->ID, $key, $record);
                    }
                }else{
                add_post_meta($post->ID, $key, $data);
                }
            }
        },
        'show_in_rest'    => true,
        'schema'          => null,
    )
  );
}
add_action( 'rest_api_init', 'rest_post_meta' );