Using WordPress ‘rest_filter_response_fields()’ PHP function

The rest_filter_response_fields() WordPress PHP function filters the REST API response to include only a white-listed set of response object fields.

Usage

rest_filter_response_fields( $response, $server, $request );

Parameters

  • $response (WP_REST_Response) – Required. The current response being served.
  • $server (WP_REST_Server) – Required. The ResponseHandler instance (usually WP_REST_Server).
  • $request (WP_REST_Request) – Required. The request that was used to make the current response.

More information

See WordPress Developer Resources: rest_filter_response_fields

Examples

Filter post fields in REST API response

This example filters the post fields in the REST API response to include only id, title, and content.

add_filter( 'rest_prepare_post', 'filter_post_fields', 10, 3 );

function filter_post_fields( $response, $post, $request ) {
    $white_listed_fields = array( 'id', 'title', 'content' );
    return rest_filter_response_fields( $response, $white_listed_fields, $request );
}

Filter user fields in REST API response

This example filters the user fields in the REST API response to include only id, username, and email.

add_filter( 'rest_prepare_user', 'filter_user_fields', 10, 3 );

function filter_user_fields( $response, $user, $request ) {
    $white_listed_fields = array( 'id', 'username', 'email' );
    return rest_filter_response_fields( $response, $white_listed_fields, $request );
}

Filter comment fields in REST API response

This example filters the comment fields in the REST API response to include only id, author_name, and content.

add_filter( 'rest_prepare_comment', 'filter_comment_fields', 10, 3 );

function filter_comment_fields( $response, $comment, $request ) {
    $white_listed_fields = array( 'id', 'author_name', 'content' );
    return rest_filter_response_fields( $response, $white_listed_fields, $request );
}

Filter custom post type fields in REST API response

This example filters the custom post type ‘portfolio’ fields in the REST API response to include only id, title, and date.

add_filter( 'rest_prepare_portfolio', 'filter_portfolio_fields', 10, 3 );

function filter_portfolio_fields( $response, $portfolio, $request ) {
    $white_listed_fields = array( 'id', 'title', 'date' );
    return rest_filter_response_fields( $response, $white_listed_fields, $request );
}

Filter taxonomy fields in REST API response

This example filters the taxonomy fields in the REST API response to include only id, name, and slug.

add_filter( 'rest_prepare_taxonomy', 'filter_taxonomy_fields', 10, 3 );

function filter_taxonomy_fields( $response, $taxonomy, $request ) {
    $white_listed_fields = array( 'id', 'name', 'slug' );
    return rest_filter_response_fields( $response, $white_listed_fields, $request );
}