Random WordPress Function

Learn about a new WordPress function every day!


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 response to only include specific fields for 'post' context
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
    if ( 'post' === $context ) {
        $data = array_intersect_key( $data, array_flip( array( 'id', 'title', 'content' ) ) );
    }
    return $data;
}, 10, 2 );
// Example 2: Modify response based on different contexts such as 'view' and 'edit'
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
    if ( 'view' === $context ) {
        $data['modified_date'] = get_the_modified_date( 'Y-m-d H:i:s', $data['id'] );
    } elseif ( 'edit' === $context ) {
        $data['author_name'] = get_the_author_meta( 'display_name', $data['author'] );
    }
    return $data;
}, 10, 2 );
// Example 3: Exclude certain fields from response for 'category' context
add_filter( 'rest_filter_response_by_context', function( $data, $context ) {
    if ( 'category' === $context ) {
        unset( $data['description'] );
    }
    return $data;
}, 10, 2 );