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 );
custom post type example filter:
function projectPost_remove_extra_data( $data, $post, $context ) {
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'] );
return $data;
}
add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );
For wp-api v1.x, you need to extend
WP_JSON_CustomPostType
. There is an example in the pages file (class-wp-json-pages.php
)Replace “Pages” with “MyCustomPostTypes” and page with “mycustomposttype”. Just be careful not to rename internal WordPress code that also uses the term
page
Note: probably best to add this as a plugin rather than change the JSON-WP-API plugin
If possible, only the examples shown in internet is:
and right is:
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
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.
It should be no different to remove data from custom post types than from the built-in post types. Have you confirmed that your API call is actually returning your CPTs? First, you should look at the value of what is returned from:
http://yourwebsite.com/wp-json/posts/types
. Assuming that your CPT type shows up there, you should be able to query for items of that type, e.g.product
, by calling:http://yourwebsite.com/wp-json/posts?type=product
.In other words, you should not change the name of the filter: you still want to tie into
json_prepare_post
. If you want to make your filter sensitive to post type and only remove certain fields if you have a CPT you could do something like:You can find more documentation in the WP API Getting Started Guide.