1

I'm using 'WP REST API Version 2.0-beta12" by http://wp-api.org/ to use REST API, available via HTTP of my site's data in simple JSON format. I have formatted my json output to limit reponse field while list post API - http://example.com/wp-json/wp/v2/posts using rest_prepare_post as follows,

function api_remove_extra_data( $data, $post, $context ) {
    // We only want to modify the 'view' context, for reading posts
    if ( $context !== 'view' || is_wp_error( $data ) ) {
        // Here, we unset any data we don't want to see on the front end:
        unset ( $data->data ['link']); 
        unset ( $data->data ['date_gmt']);
        unset ( $data->data ['modified']);
        unset ( $data->data ['modified_gmt']);
        unset ( $data->data ['type']);
        unset ( $data->data ['content']);
        unset ( $data->data ['excerpt']);
        unset ( $data->data ['author']);
        // continue unsetting whatever other fields you want
        return $data;
    }

}

add_filter( 'rest_prepare_post', 'api_remove_extra_data', 12, 3 );

It works great. But I need full post data in single post API call such as

http://example.com/wp-json/wp/v2/posts/1077

Wordpress version:  4.4.2

Plugin Version : WP REST API 2.0-beta12

By using above filter both posts list API and view single post API return only limited response. How can I get all post data in post single (http://example.com/wp-json/wp/v2/posts/1077) API by keeping limited response in posts list API?

1 Answer 1

3

Since you're filtering with the rest_prepare_{post_type} filter, you could restrict it to the WP_REST_Posts_Controller::get_items() callback, with the rest_{post_type}_query filter:

add_filter( 'rest_post_query', function( $args )
{
    add_filter( 'rest_prepare_post', 'api_remove_extra_data', 12, 3 );
    return $args;
} );

where the post type is post.

Note that in general we always want to return the filter value and I don't follow the logic your api_remove_extra_data() callback. Maybe it's a relic from version 1.x?

This is how the filter is now defined in version 2:

/**
 * Filter the post data for a response.
 *
 * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post
 * being prepared for the response.
 *
 * @param WP_REST_Response   $response   The response object.
 * @param WP_Post            $post       Post object.
 * @param WP_REST_Request    $request    Request object.
*/
return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.