[wp-trac] [WordPress Trac] #62855: Add object_id to WP_REST_Meta_Fields::prepare_value_for_response()
WordPress Trac
noreply at wordpress.org
Fri Jan 24 08:42:41 UTC 2025
#62855: Add object_id to WP_REST_Meta_Fields::prepare_value_for_response()
-------------------------+-------------------------------------
Reporter: rilwis | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: REST API | Version: trunk
Severity: normal | Keywords: 2nd-opinion needs-patch
Focuses: rest-api |
-------------------------+-------------------------------------
The method `WP_REST_Meta_Fields::prepare_value_for_response()` accepts 3
parameters: `$value`, `$request` and `$args`. It doesn't include the info
about the current item (post or term) that being retrieved data. This
makes it impossible to get the value for the current **term** if we use
`prepare_callback`:
{{{#!php
<?php
protected function prepare_value_for_response( $value, $request, $args ) {
if ( ! empty( $args['prepare_callback'] ) ) {
$value = call_user_func( $args['prepare_callback'],
$value, $request, $args );
}
return $value;
}
}}}
So, if you register a meta for **terms** like this:
{{{#!php
<?php
$args = [
'type' => 'string',
'single' => true,
'show_in_rest' => [
'prepare_callback' => 'my_callback_function',
],
];
register_meta( 'term', 'my_meta', $args );
}}}
Then inside `my_callback_function`, you can't get the value for the
current term, especially when you request the data via `/wp-
json/v2/wp/categories` for example.
This issue doesn't happen for **posts**, since WordPress sets the global
`$post` object, so we can get it with `get_post()`. But there are no
equivalents for **terms**.
Solution: I'd suggest setting the `object_id` inside `$args` to pass to
the `prepare_value_for_response`. This way, developers can get the current
term and thus, can get the correct data.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/62855>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list