Opened 4 weeks ago
Last modified 3 weeks ago
#62855 new enhancement
Add object_id to WP_REST_Meta_Fields::prepare_value_for_response()
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | trunk |
Component: | REST API | Keywords: | 2nd-opinion has-patch |
Focuses: | rest-api | Cc: |
Description
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 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 $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.
Change History (1)
This ticket was mentioned in PR #8216 on WordPress/wordpress-develop by @debarghyabanerjee.
3 weeks ago
#1
- Keywords has-patch added; needs-patch removed
Trac Ticket: Core-62855
## Summary
WP_REST_Meta_Fields::prepare_value_for_response()
method accepts three parameters:$value
,$request
, and$args
. However, it does not include information about the current item (e.g., post or term) being retrieved, which leads to issues when preparing data for terms. Specifically, when using the prepare_callback function, it's impossible to access the current term's data, particularly when making requests like/wp-json/v2/wp/categories
.$post
object, allowing functions likeget_post()
to retrieve the current post. However, there is no equivalent for terms, which causes the gap in data handling for terms.## Solution
$args
and passing it toprepare_value_for_response()
. This allows developers to access the current term (or post) within the callback, ensuring that the correct data is returned, especially for taxonomies like categories.## Changes
$args
in the call to prepare_value_for_response().## Why