I have created a custom post type and I got it to show in the REST API. I have also registered a custom field using the following code :
function slug_get_post_meta_cb( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
function slug_update_post_meta_cb( $value, $object, $field_name ) {
return update_post_meta( $object[ 'id' ], $field_name, $value );
}
add_action( 'rest_api_init', function() {
register_rest_field( 'custom_type',
'myfield',
array(
'get_callback' => 'slug_get_post_meta_cb',
'update_callback' => 'slug_update_post_meta_cb',
'schema' => array(
'type' => 'string',
'context' => array( 'view', 'edit' )
),
)
);
I'm using jQuery to create an ajax POST request in order to create a new custom post with the following javascript code :
jQuery.ajax( {
url: requete.api,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
},
data:{
title : myData.title,
content: myData.content,
status: "publish",
myfield: "Stop flying"
}
} ).done( function ( response ) {
console.log( response );
} );
The posts are created all right, by without the custom field myfield
. It does show up as part of the custom post object in the response to a GET request, but as an empty array. I also tried to set it as myfield : ["Stop flying"]
, and as meta : {myfield: "Stop flying"}
, to no avail.
I am aware of the other WP function to register a meta field (register_meta
). However since the documentation reads that it cannot be applied to a custom post type only I chose to use register_rest_field instead.
Any idea what I'm doing wrong ?