However, this CPT also includes quite a few Post Meta Fields generated by Custom Meta Boxes and Fields for WordPress. These fields include things like:
_ecmb_supporting_bands
_ecmb_tickets_avail
_ecmb_event_agelim
And by default these fields aren’t returned by the JSON API… I’ve tried to run queries like:
Or without quotes around the meta key: https://public-api.wordpress.com/rest/v1/sites/MYSITE/posts/?type=events&number=100&meta_key=_ecmb_supporting_bands
Unfortunately this doesn’t work. Does anyone know how I can return these custom meta fields in my JSON response?
2 Answers 2
From the documentation:
According to the JetPack JSON API docs:
By default, all metadata keys are allowed in the API, as long as they
are not protected keys. Any metadata key that starts with _ is by
default protected. Protected metadata keys can, however, be accessed
and edited by users with the edit_post_meta (used for editing and
viewing), add_post_meta and delete_post_meta capabilities as
appropriate for each operation. We’ve also added a filter
rest_api_allowed_public_metadata that allows you to specifically
whitelist certain metadata keys to be accessed by any user, even if
that key is protected.
so the rest_api_allowed_public_metadata filter is what you are looking for.
From the source code:
If you check the JetPack’s source code, you will find this part:
function is_metadata_public( $key ) {
if ( empty( $key ) )
return false;
// whitelist of post types that can be accessed
if ( in_array( $key, apply_filters( 'rest_api_allowed_public_metadata', array() ) ) )
return true;
return false;
}
in the file class.json-api-endpoints.php.
You can also check out the allow_bbpress_public_metadata() function here to see how to implement this rest_api_allowed_public_metadata filter.
Example:
Here is a similar example for your case:
/**
* Whitelist protected meta keys
*
* @param array $allowed_meta_keys
* @return array $allowed_meta_keys
*/
function custom_rest_api_allowed_public_metadata( $allowed_meta_keys )
{
// only run for REST API requests
if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST )
return $allowed_meta_keys;
$allowed_meta_keys[] = '_ecmb_supporting_bands';
$allowed_meta_keys[] = '_ecmb_tickets_avail';
$allowed_meta_keys[] = '_ecmb_event_agelim';
return $allowed_meta_keys;
}
add_filter( 'rest_api_allowed_public_metadata', 'custom_rest_api_allowed_public_metadata' );
with the JSON output similar to this one:
"metadata":[{"id":"196711","key":"_ecmb_event_agelim","value":"18"},
{"id":"196709","key":"_ecmb_supporting_bands","value":"The Rolling Stones"},
{"id":"196710","key":"_ecmb_tickets_avail","value":"5500"}]