Removing fields from the JSON response

I am using the WP REST API (WP API) and am retrieving the posts with this call below.

wp-json/posts

There are 170 posts and the JSON file is 3.1MB which takes about 9 seconds to download. When pulling the posts the only data I need is the title and featurd image, therefore 99% of the JSON file is not needed.

Read More

I have been looking at this method below that removes fields from the response, it works to an extent but still doesn’t remove fields such as ID and author.

function remove_extra_data( $data, $post, $context ) {
  unset( $data['ID'] );
  unset( $data['status'] );
  unset( $data['excerpt'] );
  unset( $data['type'] );
  unset( $data['author'] );
  unset( $data['content'] );
  unset( $data['parent'] );
  unset( $data['date'] );
  unset( $data['modified'] );
  unset( $data['format'] );
  unset( $data['slug'] );
  unset( $data['guid'] );
  unset( $data['menu_order'] );
  unset( $data['comment_status'] );
  unset( $data['ping_status'] );
  unset( $data['sticky'] );
  unset( $data['date_tz'] );
  unset( $data['date_gmt'] );
  unset( $data['modified_tz'] );
  unset( $data['modified_gmt'] );
  unset( $data['meta'] );
  return $data;
}

add_filter( 'json_prepare_post', 'remove_extra_data', 10, 3 );

So what is the best method to remove all unwanted fields included fields that have nested content?

Related posts

1 comment

  1. If the JSON is being decoded strictly as an array, and not an object, you could use something like array_filter() to filter out those properties which you don’t want.

    // This will only work in PHP 5.6+
    $keys = [
        'ID',
        'author',
    ];
    return array_filter($data, function($k) use ($keys) {
        return in_array($k, $keys, true);
    }, ARRAY_FILTER_USE_KEY);
    

Comments are closed.