Function Signature:
rest_filter_response_by_context
Function Description:
Filters the response to remove any fields not available in the given context.
Function Examples:
⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Filter the REST API response to only include specific fields based on context
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
if ( 'view' === $context ) {
$data['id'] = $data['id'];
$data['title'] = $data['title']['rendered'];
}
return $data;
}, 10, 2 );
// Example 2: Modify the REST API response based on the user's role
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
if ( current_user_can( 'administrator' ) && 'edit' === $context ) {
$data['author'] = get_userdata( $data['author'] )->user_login;
}
return $data;
}, 10, 2 );
// Example 3: Customize the REST API response for specific post types
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
if ( 'view' === $context && 'post' === $data['type'] ) {
$data['excerpt'] = strip_tags( $data['excerpt']['rendered'] );
}
return $data;
}, 10, 2 );