[wp-trac] [WordPress Trac] #44432: Sometimes, an array is passed to the get_callback provided to register_rest_field() instead of an object

WordPress Trac noreply at wordpress.org
Fri Jun 22 04:41:59 UTC 2018


#44432: Sometimes, an array is passed to the get_callback provided to
register_rest_field() instead of an object
--------------------------+-----------------------------
 Reporter:  salzano       |      Owner:  (none)
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  REST API      |    Version:  4.9.6
 Severity:  normal        |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 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
 [https://developer.wordpress.org/reference/functions/register_rest_field/#comment-2260].
 It certainly feels like a bug.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/44432>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list