Search code examples
wordpresswordpress-rest-api

How to nest a field under another using register_rest_field in WP REST API


I found that I can´t achieve this. See SOLUTION section at the bottom.

I am using function register_rest_field to publish some custom meta fields in Wordpress REST API.

The API response looks something like this:

id: 1
meta: []
my_custom_field: "some value"
my_another_custom_field:
    0: "Alfa"
    1: "Bravo"
    2: "Charlie"

What I want to accomplish is to nest my custom fields under the meta field. So it will result in something like this:

id: 1
meta:
    my_custom_field: "some value"
    my_another_custom_field:
        0: "Alfa"
        1: "Bravo"
        2: "Charlie"

I have tried using register_meta function instead. It does help with nesting under the meta field. But it support only scalar values, and I need to display array values too (as in the example field my_another_custom_field). So I have to stick on the register_rest_field function.

Is there a way to nest custom fields under the meta field with the register_rest_field function?


Solution

  • I now know it is not possible. You can either expose fields with array type (with register_rest_field function) OR you can expose your fields under the meta attribute (with register_meta function), that can´t be of the array type. But not both.