[wp-trac] [WordPress Trac] #43502: `WP_REST_Posts_Controller::prepare_item_for_response()` doesn't reset postdata after calling setup_postdata()
WordPress Trac
noreply at wordpress.org
Thu Mar 8 16:45:43 UTC 2018
#43502: `WP_REST_Posts_Controller::prepare_item_for_response()` doesn't reset
postdata after calling setup_postdata()
---------------------------+-----------------------------
Reporter: gerbenvandijk | Owner:
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: REST API | Version: 4.9.4
Severity: normal | Keywords:
Focuses: rest-api |
---------------------------+-----------------------------
Hi all,
I seem to have stumbled upon a small oversight in
`WP_REST_Posts_Controller::prepare_item_for_response()` , where it doesn't
reset postdata after calling `setup_postdata()`, rendering this part of
the API useless for developers who want to use this API in their custom
code.
Ran into it while writing a custom function, that uses this part of the
API to convert a regular post object into an object that matches the json
scheme of the API.
I’ve fixed it temporarily by doing setting `$GLOBALS[ 'post' ] =
$original_post_id` in my function (and by passing `original_post_id` as
parameter to my function) - but it seems to me that this should be fixed
in core.
{{{#!php
function convert_post_object_to_rest_response($post)
{
global $wp_rest_server;
$post_type = get_post_type_object($post->post_type);
$request = WP_REST_Request::from_url(rest_url(sprintf('wp/v2/%s/%d',
$post_type->rest_base, $post->ID)));
$request = rest_do_request($request);
$data = $wp_rest_server->response_to_data($request, isset($_GET[
'_embed' ]));
return $data;
}
}}}
It returns the right data, which is great - but when i in turn use this
function to supply a field in one of my endpoints with this dat, all
fields below it seem to inherit the ID i’ve passed.
i’ve traced this back to
`WP_REST_Posts_Controller::prepare_item_for_response`, where it’s doing a
`setup_postdata` call without resetting it later.
For now i’ve fixed it by setting `$GLOBALS[ 'post' ] = $original_post_id`
in my function (and by passing `original_post_id` as parameter to my
function), but I figured i'd report it here so it can be fixed from the
core.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/43502>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list