Using WordPress ‘rest_filter_response_by_context()’ PHP function

The rest_filter_response_by_context() WordPress PHP function filters the response to remove any fields not available in the given context.

Usage

$filtered_response = rest_filter_response_by_context( $response_data, $schema, $context );

Parameters

  • $response_data (array|object): Required. The response data to modify.
  • $schema (array): Required. The schema for the endpoint used to filter the response.
  • $context (string): Required. The requested context.

More information

See WordPress Developer Resources: rest_filter_response_by_context()

Examples

Filter post response data

In this example, we filter the post response data by the ‘view’ context.

// Define the post response data
$post_response_data = [
    'id' => 123,
    'title' => 'Example Post',
    'content' => 'This is an example post content.',
];

// Define the post schema
$post_schema = [
    'id' => [
        'context' => ['view', 'edit'],
    ],
    'title' => [
        'context' => ['view', 'edit'],
    ],
    'content' => [
        'context' => ['edit'],
    ],
];

// Filter the post response data by 'view' context
$filtered_response = rest_filter_response_by_context( $post_response_data, $post_schema, 'view' );

// The $filtered_response will contain only the 'id' and 'title' fields

Filter custom endpoint response data

In this example, we filter custom endpoint response data by the ’embed’ context.

// Define the custom endpoint response data
$custom_response_data = [
    'id' => 456,
    'name' => 'John Doe',
    'email' => '[email protected]',
];

// Define the custom endpoint schema
$custom_schema = [
    'id' => [
        'context' => ['view', 'embed'],
    ],
    'name' => [
        'context' => ['view', 'embed'],
    ],
    'email' => [
        'context' => ['view'],
    ],
];

// Filter the custom endpoint response data by 'embed' context
$filtered_response = rest_filter_response_by_context( $custom_response_data, $custom_schema, 'embed' );

// The $filtered_response will contain only the 'id' and 'name' fields

Filter term response data

In this example, we filter term response data by the ‘edit’ context.

// Define the term response data
$term_response_data = [
    'id' => 789,
    'name' => 'Category 1',
    'slug' => 'category-1',
];

// Define the term schema
$term_schema = [
    'id' => [
        'context' => ['view', 'edit'],
    ],
    'name' => [
        'context' => ['view', 'edit'],
    ],
    'slug' => [
        'context' => ['edit'],
    ],
];

// Filter the term response data by 'edit' context
$filtered_response = rest_filter_response_by_context( $term_response_data, $term_schema, 'edit' );

// The $filtered_response will contain all fields: 'id', 'name', and 'slug'