Remove _links object from wp rest api response using filter or hook

I have removed unnecessary data unset($data->data['field_name'])

from json output. For this I am using a wordpress filter rest_prepare_

.

But how do we remove the _links object from the JSON output?

+3


source to share


4 answers


It's not a good solution, but work it.



function contract_remove_links( $data, $post, $context ) {

    $data->remove_link( 'collection' );
    $data->remove_link( 'self' );
    $data->remove_link( 'about' );
    $data->remove_link( 'author' );
    $data->remove_link( 'replies' );
    $data->remove_link( 'version-history' );
    $data->remove_link( 'https://api.w.org/featuredmedia' );
    $data->remove_link( 'https://api.w.org/attachment' );
    $data->remove_link( 'https://api.w.org/term' );
    $data->remove_link( 'curies' );

    return $data;
}

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

      

+2


source


I don't know how to disable , but you can set which variables to return.



function prepare_rest($data, $post, $request){
    return [
        'id'    => $data->data['id'],
        'title' => $data->data['title']['rendered']
    ];
}

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

      

+1


source


Unfortunately, you cannot delete it, its protected.

    unset( $data->links );

    PHP Fatal error:  Uncaught Error: Cannot access protected property WP_REST_Response::$links 

    /wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php(311)
        Line 1567:  $response->add_links( $this->prepare_links( $post ) );
        Line 1608:  protected function prepare_links( $post ) {

      

0


source


rest_prepare_post

- correct filter, but the field is _links

dynamically generated by WordPress. Therefore, you cannot delete things directly.

you can add your own link

to this parameter or remove the default link from "_links".

Here is the code ....

add_filter( 'rest_prepare_post', function ( $response ) {
$response->add_link( 'yourrel', rest_url( 'yourendpoint/thing' ), array(
    'embeddable' => true,
) );

$response->remove_link( 'collection' );

return $response;
} );

      

0


source







All Articles