Tell us what you are trying to do?
I have a repeated field group name "foreign-languages" for a CPT I have already made name "candidate-profile".
What I'm trying to do is to get all candidate profiles and for each profile, get all foreign-languages through the WP REST API.
I have already enabled the REST API for the foreign-languages but I can't expose the toolset custom fields (that's the actual quest), probably I'm missing something very minor.
My current code is:
```
add_filter( 'register_post_type_args', 'expose_RGF_CPT', 10, 2 );
function expose_RGF_CPT( $args, $post_type ) {
if ( 'foreign-languages' === $post_type ) {
$args['show_in_rest'] = true;
$args['rest_base'] = 'foreign-languages';
$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
}
return $args;
}
```
Could you please assist me?
Thank you in advance
Hello and thank you for contacting Toolset support.
I tried to expose RFGs on my local setup, but the custom fields were not published. However, I was able to find 2 workarounds.
We can either whitelist the fields so they can appear on a .meta key in the response. Or we can register our own fields for the REST response.
Whitelisting the custom field can be done using the register_post_meta function. Assuming that the RFG slug is "cpt-books-comments" and the field slug is "comment", the following code should work. Note that the field slug is prefixed with "wpcf-"
register_post_meta('cpt-books-comments', 'wpcf-comment',
[
'show_in_rest' => true,
]
);
https://developer.wordpress.org/reference/functions/register_post_meta/
Registering your own fields can be done using the rest_api_init function. Something like:
add_action( 'rest_api_init', function() {
register_rest_field( 'cpt-books-comments',
'comment',
array(
'get_callback' => 'slug_get_post_meta_cb',
'update_callback' => 'slug_update_post_meta_cb',
'schema' => null,
)
);
});
function slug_get_post_meta_cb( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], 'wpcf-' . $field_name );
}
function slug_update_post_meta_cb( $value, $object, $field_name ) {
return update_post_meta( $object[ 'id' ], 'wpcf-' . $field_name, $value );
}
https://developer.wordpress.org/reference/hooks/rest_api_init/
You can use Toolset functions to get formatted data https://toolset.com/documentation/customizing-sites-using-php/functions/
Another workaround would be to build your own REST_Controller class and use it in your initial code instead of the WP_REST_Posts_Controller class.
https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/
I hope this helps. Let me know if you have any questions.
My issue is resolved now. Thank you!
I chose the first approach and I whitelisted some of the desired fields.
Thank you very much for your quick response!