0

I have created an empty user meta field for a user called phone_number via the add_user_meta() function.

When I use the get_user_meta function, I can see an empty string for the meta field which is what I would expect.

But when I access the endpoint for the user via the REST API e.g. /wp-json/wp/v2/users/8, there is an empty meta array, why?

How do I update the phone_number empty meta field I created earlier via the REST API?

0

I hope to help you put in the right direction. Be welcome to the community and don't forget to update your question with the code that you tried in order to give more examples to the community.

Let's get to the issue.

First, you have added the user data in the meta table, through the add_user_meta function. That's right to save the data, but add_user_meta does not exposes the field itself in the REST API. You need to register first that field into the API, for the users type:

add_action('rest_api_init', function() {
    register_rest_field( 'user', 'phone_number', [
        'get_callback'    => 'get_user_phone_number',
        'update_callback' => 'update_user_phone_number',
        'schema'          => [
                                'type'        => 'string',
                                'description' => 'The phone number ...',
                                'context'     => [ 'view', 'edit' ],
                             ],
    ]);
});

function get_user_phone_number( $user, $field_name, $request ) { 
    return get_user_meta( $user[ 'id' ], $field_name, true );
}

function update_user_phone_number( $user, $meta_value ) { 
    update_user_meta( $user[ 'id' ], 'phone_number', $meta_value );
}

While the schema argument is frequently neglected, it offers you a lot in terms of validation for basic types of fields, you could even make your own validation function in order to avoid invalid information, but for a lot of things, just using the right type of field in the schema will help you a lot.

  • Thanks for your help, I've setup my field successfully through the example you gave, however if I send a PUT request via Postman to the endpoint, the field value will not change and I'm not given any errors. But I change the field to "description" it will update successfully. Is there something I'm missing? – Tom May 20 at 11:47
  • Could you share please the code that you are using right now? I find weird the "change... to 'description'", maybe your use case is a bit more specific and we could learn more of you sharing the problem at this state. I'd recommend you sharing in another question, to be more specific at the solution. – Jesús Franco May 20 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.