I have removed unwanted data by unset($data->data['field_name'])
from json output. For this I am using wordpress filter rest_prepare_
.
But how we remove _links object from JSON output?
I don’t know how to unset, 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);
This is not very good solution but work.
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 );
Gotta be careful removing stuff from the API, but if you're sure you want to remove this, it can be done like this:
function so_45027789_rest_prepare_post($data, $post, $request)
{
foreach($data->get_links() as $_linkKey => $_linkVal) {
$data->remove_link($_linkKey);
}
return $data;
}
add_filter('rest_prepare_post', 'so_45027789_rest_prepare_post', 1, 3);
I'd recommend only doing so if you're explicitly asking for a smaller response in your implementation with the API, thereby leaving default usage of the API untouched, like via a query variable:
function so_45027789_rest_prepare_post($data, $post, $request)
{
$params = $request->get_params();
if(isset($params['_minimal'])) {
foreach($data->get_links() as $_linkKey => $_linkVal) {
$data->remove_link($_linkKey);
}
}
return $data;
}
add_filter('rest_prepare_post', 'so_45027789_rest_prepare_post', 1, 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With