How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field.
The function i have right now:
<?php
function portal_add_user_field() {
register_rest_field( 'user', 'phonenumber',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function( $user, $meta_key, $meta_value, $prev_value ) {
$ret = update_user_meta( array( $user, $meta_key, $meta_value );
return true;
},
'schema' => array(
'description' => __( 'user phonenumber' ),
'type' => 'string'
),
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field' );
I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field)
updateUser: function () {
var data = {
username: this.username,
email: this.email,
first_name: this.firstname,
last_name: this.lastname,
meta: {
phonenumber: this.phonenumber
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));