I can already unset (remove specifics from normal posts) in the json returned from the WordPress API. I actually use the following below from this example: https://css-tricks.com/using-the-wp-api-to-fetch-posts/
What I am having trouble with and can’t figure out, is how to change this so it unsets data from a Custom Post Type
Thoughts?
function qod_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
unset( $data['featured_image'] );
//etc etc
return $data;
}
add_filter( 'json_prepare_post', 'qod_remove_extra_data', 12, 3 );
new example with custom post type **
function projectPost_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
return $data;
}
add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );
If possible, only the examples shown in internet is:
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
return $data;
}
// Here, we unset any data we do not want to see on the front end:
unset($data['author']);
unset($data['status']);
// Continue unsetting whatever other fields you want return $ data;
}
add_filter('json_prepare_post', 'qod_remove_extra_data', 12, 3);
and right is:
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
unset ( $data->data['excerpt']); //Example
unset ($data->data['content']); //Example
unset ($data->data['name field to remove']);
//or
unset ($data->data['name field to remove']['name subfield if you only want to delete the sub-field of field']);
return $data;
}
}
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
IMPORTANT:
Is:
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
Not:
add_filter('json_prepare_post', 'qod remove extra_data', 12, 3); //WRONG (No underscores)
If is Custom Post Type:
add_filter('rest_prepare_{$post_type}', 'qod_remove_extra_data', 12, 3);
EXAMPLE: Name post type = product;
add_filter('rest_prepare_product', 'qod_remove_extra_data', 12, 3);
With this code can remove the fields that you want the JSON. By using rest_prepare}_{$ post_type decide that you eliminated every post_type fields, thus only affected the post_type you want and not all.