When working with the WordPress REST API we sometimes have to update custom post meta for a (custom post type) post. In my case, I am using the available REST endpoints but I did want to add some extra data to the GET request, and wanted to make it possible to update that data as well.
It’s actually quite easy to get this to work in WordPress, we’ll hook into the rest_api_init
and use the register_rest_field
function to add this features, like in the example below:
add_action( 'rest_api_init', array( $this, 'add_fields' ) );
public function add_fields() {
register_rest_field(
'session',
'start_time',
array(
'get_callback' => function() {
return get_post_meta( get_the_ID(), '_sympose_session_start', true );
},
'update_callback' => function( $value, $object, $field_name ) {
return update_post_meta($object->ID, '_sympose_session_start', $value );
},
)
);
}
In the example above we’re extending the session post type with a “start_time” field. The “start_time” field is saved as post meta with the _sympose_session_start
key. Change these variables to your own and you’re good to go!
We can then use something like a fetch request to get and update these fields like in the example below:
let post_id = 10;
let start_time_value = '10:00';
fetch(wpApiSettings.root + "wp/v2/session/" + post_id, {
method: "POST",
headers: {
"X-WP-Nonce": wpApiSettings.nonce,
'Content-Type': 'application/json',
},
body: JSON.stringify({
start_time: start_time_value,
}),
})
.then(res => res.json())
.then(result => {
console.log(result);
});
Note: Consider these examples as starting points. In my case, they’re used for a PoC and security has not been considered in yet as that also makes the code more difficult to understand.
Happy developing!
Leave a Reply