When using register_rest_field()
to add fields to terms in the WordPress REST API, the $object sent to your get_callback
function will be an array instead of an object like the documentation describes.
An object will still be passed, sometimes, too. Here is an example of how I work around this problem:
function add_api_term_fields() {
//location-phone-hours
register_rest_field( 'location', 'location-phone-hours', array(
'get_callback' => array( $this, 'get_term_meta_via_rest' ),
'update_callback' => array( $this, 'set_term_meta_via_rest' ),
'schema' => array(
'description' => __( 'An array of phone numbers and hours of operation for this location.', 'inventory-portal' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
) );
}
static function get_term_meta_via_rest( $term, $attr, $request, $object_type ) {
$term_id = 0;
if( is_array( $term ) ) {
$term_id = $term['id']
} else {
$term_id = $term->term_id;
}
return maybe_serialize( get_term_meta( $term_id, $attr, true ) );
}
Why is this happening? See the definition of prepare_item_for_response()
method on line 683 of wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php. The call to add_additional_fields_to_object()
on line 725 is the method that passes an array to your get_callback
.
Perhaps this is an acceptable design. I believe the only reference to the data type of $object in the documentation is this comment. It certainly feels like a bug.
Comments
One response to “Sometimes, an array is passed to the get_callback provided to register_rest_field() instead of an object”
Corey, thanks for opening an issue for this on WordPress trac at https://core.trac.wordpress.org/ticket/44432 ?