I am trying to register a rest field for my custom taxonomy’s custom meta fields. I followed the tutorial at Modifying Responses . The code worked great for adding a rest field for post meta data for custom post types, but when I tried the following code to add a rest field for my custom taxonomy, it didn’t work. Is it possible to do what I am trying to do?
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_location' );
//REGISTER
function register_rest_field_for_custom_taxonomy_location() {
register_rest_field( 'location',
'location_code',
array(
'get_callback' => 'location_get_term_meta',
'update_callback' => 'location_update_term_meta',
'schema' => null;
)
);
}
//WRITE
function location_update_term_meta_field( $value, $object, $field_name ) {
if ( ! $value || ! is_string( $value ) ) {
return;
}
return update_term_meta( $object->ID, $field_name, $value );
}
//READ
function location_get_term_meta_field( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ], $field_name, true );
}
1 Answer
Both callbacks in the register_rest_field_for_custom_taxonomy_location() function are misspelled.
change
'get_callback' => 'location_get_term_meta',
'update_callback' => 'location_update_term_meta',
to
'get_callback' => 'location_get_term_meta_field',
'update_callback' => 'location_update_term_meta_field',
Register Code
function register_rest_field_for_custom_taxonomy_location() {
register_rest_field( 'location',
'location_code',
array(
'get_callback' => 'location_get_term_meta_field',
'update_callback' => 'location_update_term_meta_field',
'schema' => null,
)
);